Minor code cleanup.
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
index d6e0e09..fb31ccf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2007 Internet2
+ *  Copyright 2001-2010 Internet2
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 /**
  * XMLServiceProvider.cpp
  *
- * XML-based SP configuration and mgmt
+ * XML-based SP configuration and mgmt.
  */
 
 #include "internal.h"
 #include "exceptions.h"
+#include "version.h"
 #include "AccessControl.h"
 #include "Application.h"
 #include "RequestMapper.h"
 #include "ServiceProvider.h"
 #include "SessionCache.h"
 #include "SPConfig.h"
+#include "SPRequest.h"
 #include "handler/SessionInitiator.h"
 #include "remoting/ListenerService.h"
 #include "util/DOMPropertySet.h"
 #else
 # error "Supported logging library not available."
 #endif
+#include <algorithm>
 #include <xercesc/util/XMLUniDefs.hpp>
 #include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/version.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/ReloadableXMLFile.h>
+#include <xmltooling/util/TemplateEngine.h>
+#include <xmltooling/util/Threads.h>
 #include <xmltooling/util/XMLHelper.h>
 
 #ifndef SHIBSP_LITE
 # include "attribute/resolver/AttributeExtractor.h"
 # include "attribute/resolver/AttributeResolver.h"
 # include "security/PKIXTrustEngine.h"
+# include "security/SecurityPolicyProvider.h"
 # include <saml/SAMLConfig.h>
+# include <saml/version.h>
 # include <saml/binding/ArtifactMap.h>
 # include <saml/binding/SAMLArtifact.h>
 # include <saml/saml1/core/Assertions.h>
+# include <saml/saml2/core/Assertions.h>
 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
-# include <saml/saml2/metadata/ChainingMetadataProvider.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/MetadataProvider.h>
+# include <saml/util/SAMLConstants.h>
 # include <xmltooling/security/ChainingTrustEngine.h>
+# include <xmltooling/security/CredentialResolver.h>
+# include <xmltooling/security/SecurityHelper.h>
 # include <xmltooling/util/ReplayCache.h>
+# include <xmltooling/util/StorageService.h>
+# include <xsec/utils/XSECPlatformUtils.hpp>
 using namespace opensaml::saml2;
 using namespace opensaml::saml2p;
 using namespace opensaml::saml2md;
 using namespace opensaml;
+#else
+# include "lite/SAMLConstants.h"
 #endif
 
 using namespace shibsp;
@@ -87,7 +104,7 @@ namespace {
     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
     {
     public:
-        XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
+        XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=nullptr);
         ~XMLApplication() { cleanup(); }
 
         const char* getHash() const {return m_hash.c_str();}
@@ -102,7 +119,11 @@ namespace {
             index = props->getInt("artifactEndpointIndex");
             if (!index.first)
                 index = getArtifactEndpointIndex();
-            return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(props->getString("entityID").second),index.first ? index.second : 1);
+            pair<bool,const char*> entityID = props->getString("entityID");
+            return new SAML2ArtifactType0004(
+                SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
+                index.first ? index.second : 1
+                );
         }
 
         MetadataProvider* getMetadataProvider(bool required=true) const {
@@ -139,6 +160,10 @@ namespace {
             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
         }
 
+        void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
+        void setHeader(SPRequest& request, const char* name, const char* value) const;
+        string getSecureHeader(const SPRequest& request, const char* name) const;
+
         const SessionInitiator* getDefaultSessionInitiator() const;
         const SessionInitiator* getSessionInitiatorById(const char* id) const;
         const Handler* getDefaultAssertionConsumerService() const;
@@ -150,7 +175,7 @@ namespace {
         void receive(DDF& in, ostream& out) {
             // Only current function is to return the headers to clear.
             DDF header;
-            DDF ret=DDF(NULL).list();
+            DDF ret=DDF(nullptr).list();
             DDFJanitor jret(ret);
             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
                 header = DDF(i->first.c_str()).string(i->second.c_str());
@@ -160,12 +185,18 @@ namespace {
         }
 
         // Provides filter to exclude special config elements.
-        short acceptNode(const DOMNode* node) const;
+#ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
+        short
+#else
+        FilterAction
+#endif
+        acceptNode(const DOMNode* node) const;
 
     private:
         void cleanup();
         const XMLApplication* m_base;
         string m_hash;
+        std::pair<std::string,std::string> m_attributePrefix;
 #ifndef SHIBSP_LITE
         MetadataProvider* m_metadata;
         TrustEngine* m_trust;
@@ -176,11 +207,7 @@ namespace {
         vector<const XMLCh*> m_audiences;
 
         // RelyingParty properties
-#ifdef HAVE_GOOD_STL
         map<xstring,PropertySet*> m_partyMap;
-#else
-        map<const XMLCh*,PropertySet*> m_partyMap;
-#endif
 #endif
         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
 
@@ -197,11 +224,7 @@ namespace {
         const Handler* m_acsDefault;
 
         // maps binding strings to supporting consumer service(s)
-#ifdef HAVE_GOOD_STL
         typedef map<xstring,vector<const Handler*> > ACSBindingMap;
-#else
-        typedef map<string,vector<const Handler*> > ACSBindingMap;
-#endif
         ACSBindingMap m_acsBindingMap;
 
         // pointer to default session initiator
@@ -230,12 +253,17 @@ namespace {
         RequestMapper* m_requestMapper;
         map<string,Application*> m_appmap;
 #ifndef SHIBSP_LITE
-        map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
+        SecurityPolicyProvider* m_policy;
         vector< pair< string, pair<string,string> > > m_transportOptions;
 #endif
 
         // Provides filter to exclude special config elements.
-        short acceptNode(const DOMNode* node) const;
+#ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
+        short
+#else
+        FilterAction
+#endif
+        acceptNode(const DOMNode* node) const;
 
         void setDocument(DOMDocument* doc) {
             m_document = doc;
@@ -256,37 +284,53 @@ namespace {
     {
     public:
         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
-            m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
+            m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
 #ifndef SHIBSP_LITE
-            , m_tranLog(NULL)
+            , m_tranLog(nullptr)
 #endif
         {
         }
 
         void init() {
-            load();
+            background_load();
         }
 
         ~XMLConfig() {
+            shutdown();
             delete m_impl;
             delete m_sessionCache;
             delete m_listener;
 #ifndef SHIBSP_LITE
             delete m_tranLog;
-            SAMLConfig::getConfig().setArtifactMap(NULL);
-            XMLToolingConfig::getConfig().setReplayCache(NULL);
+            SAMLConfig::getConfig().setArtifactMap(nullptr);
+            XMLToolingConfig::getConfig().setReplayCache(nullptr);
             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
 #endif
         }
 
+#ifndef SHIBSP_LITE
+        // Lockable
+        Lockable* lock() {
+            ReloadableXMLFile::lock();
+            if (m_impl->m_policy)
+                m_impl->m_policy->lock();
+            return this;
+        }
+        void unlock() {
+            if (m_impl->m_policy)
+                m_impl->m_policy->unlock();
+            ReloadableXMLFile::unlock();
+        }
+#endif
+
         // PropertySet
         const PropertySet* getParent() const { return m_impl->getParent(); }
         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
-        pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
-        pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
-        pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
-        pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
-        pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
+        pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
+        pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
+        pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
+        pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
+        pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
         void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
         const DOMElement* getElement() const {return m_impl->getElement();}
@@ -308,7 +352,9 @@ namespace {
                 if (i!=m_storage.end())
                     return i->second;
             }
-            return NULL;
+            else if (!m_storage.empty())
+                return m_storage.begin()->second;
+            return nullptr;
         }
 #endif
 
@@ -331,23 +377,23 @@ namespace {
         }
 
         const Application* getApplication(const char* applicationId) const {
-            map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
-            return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
+            map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
+            return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
         }
 
 #ifndef SHIBSP_LITE
+        SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
+            if (required && !m_impl->m_policy)
+                throw ConfigurationException("No SecurityPolicyProvider available.");
+            return m_impl->m_policy;
+        }
+
         const PropertySet* getPolicySettings(const char* id) const {
-            map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
-            if (i!=m_impl->m_policyMap.end())
-                return i->second.first;
-            throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
+            return getSecurityPolicyProvider()->getPolicySettings(id);
         }
 
         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
-            map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
-            if (i!=m_impl->m_policyMap.end())
-                return i->second.second;
-            throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
+            return getSecurityPolicyProvider()->getPolicyRules(id);
         }
 
         bool setTransportOptions(SOAPTransport& transport) const {
@@ -364,7 +410,7 @@ namespace {
 #endif
 
     protected:
-        pair<bool,DOMElement*> load();
+        pair<bool,DOMElement*> background_load();
 
     private:
         friend class XMLConfigImpl;
@@ -381,6 +427,7 @@ namespace {
     #pragma warning( pop )
 #endif
 
+    static const XMLCh applicationId[] =        UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
     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);
     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);
     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
@@ -393,6 +440,7 @@ namespace {
     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
     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);
+    static const XMLCh _default[] =             UNICODE_LITERAL_7(d,e,f,a,u,l,t);
     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
@@ -409,13 +457,13 @@ namespace {
     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
-    static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);
     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
-    static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);
+    static const XMLCh RequestMap[] =           UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
+    static const XMLCh SecurityPolicyProvider[] = UNICODE_LITERAL_22(S,e,c,u,r,i,t,y,P,o,l,i,c,y,P,r,o,v,i,d,e,r);
     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
     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);
@@ -426,16 +474,6 @@ namespace {
     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
-
-#ifndef SHIBSP_LITE
-    class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
-    {
-    public:
-        short acceptNode(const DOMNode* node) const {
-            return FILTER_REJECT;
-        }
-    };
-#endif
 };
 
 namespace shibsp {
@@ -451,11 +489,11 @@ XMLApplication::XMLApplication(
     const XMLApplication* base
     ) : Application(sp), m_base(base),
 #ifndef SHIBSP_LITE
-        m_metadata(NULL), m_trust(NULL),
-        m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
-        m_credResolver(NULL),
+        m_metadata(nullptr), m_trust(nullptr),
+        m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
+        m_credResolver(nullptr),
 #endif
-        m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
+        m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("XMLApplication");
@@ -464,7 +502,7 @@ XMLApplication::XMLApplication(
 
     try {
         // First load any property sets.
-        load(e,NULL,this);
+        load(e,nullptr,this);
         if (base)
             setParent(base);
 
@@ -474,7 +512,7 @@ XMLApplication::XMLApplication(
         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
 #endif
 
-        // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
+        // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
         string tohash=getId();
         tohash+=getString("entityID").second;
@@ -483,6 +521,18 @@ XMLApplication::XMLApplication(
             m_hash += (DIGITS[0x0F & *ch]);
         }
 
+        // Populate prefix pair.
+        m_attributePrefix.second = "HTTP_";
+        pair<bool,const char*> prefix = getString("attributePrefix");
+        if (prefix.first) {
+            m_attributePrefix.first = prefix.second;
+            const char* pch = prefix.second;
+            while (*pch) {
+                m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
+                pch++;
+            }
+        }
+
         // Load attribute ID lists for REMOTE_USER and header clearing.
         if (conf.isEnabled(SPConfig::InProcess)) {
             pair<bool,const char*> attributes = getString("REMOTE_USER");
@@ -499,16 +549,16 @@ XMLApplication::XMLApplication(
                     if (pos)
                         *pos=0;
                     m_remoteUsers.push_back(start);
-                    start = pos ? pos+1 : NULL;
+                    start = pos ? pos+1 : nullptr;
                 }
                 free(dup);
             }
 
             attributes = getString("unsetHeaders");
             if (attributes.first) {
-                string transformedprefix("HTTP_");
+                string transformedprefix(m_attributePrefix.second);
                 const char* pch;
-                pair<bool,const char*> prefix = getString("metadataAttributePrefix");
+                prefix = getString("metadataAttributePrefix");
                 if (prefix.first) {
                     pch = prefix.second;
                     while (*pch) {
@@ -534,29 +584,30 @@ XMLApplication::XMLApplication(
                         transformed += (isalnum(*pch) ? toupper(*pch) : '_');
                         pch++;
                     }
-                    m_unsetHeaders.push_back(pair<string,string>(start,string("HTTP_") + transformed));
+
+                    m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
                     if (prefix.first)
-                        m_unsetHeaders.push_back(pair<string,string>(string(prefix.second) + start, transformedprefix + transformed));
-                    start = pos ? pos+1 : NULL;
+                        m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
+                    start = pos ? pos+1 : nullptr;
                 }
                 free(dup);
-                m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
+                m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
             }
         }
 
-        Handler* handler=NULL;
+        Handler* handler=nullptr;
         const PropertySet* sessions = getPropertySet("Sessions");
 
         // Process assertion export handler.
-        pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
+        pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
         if (location.first) {
             try {
                 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
-                exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
+                exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
                 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
                 if (exportACL.first) {
                     static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
-                    exportElement->setAttributeNS(NULL,_acl,exportACL.second);
+                    exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
                 }
                 handler = conf.HandlerManager.newPlugin(
                     samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
@@ -579,130 +630,130 @@ XMLApplication::XMLApplication(
 
         // Process other handlers.
         bool hardACS=false, hardSessionInit=false, hardArt=false;
-        const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
+        const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
         while (child) {
+            if (!child->hasAttributeNS(nullptr, Location)) {
+                auto_ptr_char hclass(child->getLocalName());
+                log.error("%s handler with no Location property cannot be processed", hclass.get());
+                child = XMLHelper::getNextSiblingElement(child);
+                continue;
+            }
             try {
-                // A handler is based on the Binding property in conjunction with the element name.
-                // If it's an ACS or SI, also handle index/id mappings and defaulting.
-                if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
-                    auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
-                    if (!bindprop.get() || !*(bindprop.get())) {
-                        log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
+                if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
+                    string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
+                    if (bindprop.empty()) {
+                        log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
+                    handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
-#ifdef HAVE_GOOD_STL
                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
-#else
-                    m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
-#endif
-                    m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
+                    m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
 
                     if (!hardACS) {
-                        pair<bool,bool> defprop=handler->getBool("isDefault");
+                        pair<bool,bool> defprop = handler->getBool("isDefault");
                         if (defprop.first) {
                             if (defprop.second) {
-                                hardACS=true;
-                                m_acsDefault=handler;
+                                hardACS = true;
+                                m_acsDefault = handler;
                             }
                         }
                         else if (!m_acsDefault)
-                            m_acsDefault=handler;
+                            m_acsDefault = handler;
                     }
                 }
-                else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
-                    auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                    if (!type.get() || !*(type.get())) {
-                        log.warn("SessionInitiator element has no type attribute, skipping it...");
+                else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
+                    string t(XMLHelper::getAttrString(child, nullptr, _type));
+                    if (t.empty()) {
+                        log.error("SessionInitiator element has no type attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
-                    handler=sihandler;
-                    pair<bool,const char*> si_id=handler->getString("id");
+                    SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
+                    handler = sihandler;
+                    pair<bool,const char*> si_id = handler->getString("id");
                     if (si_id.first && si_id.second)
-                        m_sessionInitMap[si_id.second]=sihandler;
+                        m_sessionInitMap[si_id.second] = sihandler;
                     if (!hardSessionInit) {
-                        pair<bool,bool> defprop=handler->getBool("isDefault");
+                        pair<bool,bool> defprop = handler->getBool("isDefault");
                         if (defprop.first) {
                             if (defprop.second) {
-                                hardSessionInit=true;
-                                m_sessionInitDefault=sihandler;
+                                hardSessionInit = true;
+                                m_sessionInitDefault = sihandler;
                             }
                         }
-                        else if (!m_sessionInitDefault)
-                            m_sessionInitDefault=sihandler;
+                        else if (!m_sessionInitDefault) {
+                            m_sessionInitDefault = sihandler;
+                        }
                     }
                 }
-                else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
-                    auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                    if (!type.get() || !*(type.get())) {
-                        log.warn("LogoutInitiator element has no type attribute, skipping it...");
+                else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
+                    string t(XMLHelper::getAttrString(child, nullptr, _type));
+                    if (t.empty()) {
+                        log.error("LogoutInitiator element has no type attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
+                    handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
                 }
-                else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
-                    auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
-                    if (!bindprop.get() || !*(bindprop.get())) {
-                        log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
+                else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
+                    string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
+                    if (bindprop.empty()) {
+                        log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
+                    handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
 
                     if (!hardArt) {
-                        pair<bool,bool> defprop=handler->getBool("isDefault");
+                        pair<bool,bool> defprop = handler->getBool("isDefault");
                         if (defprop.first) {
                             if (defprop.second) {
-                                hardArt=true;
-                                m_artifactResolutionDefault=handler;
+                                hardArt = true;
+                                m_artifactResolutionDefault = handler;
                             }
                         }
                         else if (!m_artifactResolutionDefault)
-                            m_artifactResolutionDefault=handler;
+                            m_artifactResolutionDefault = handler;
                     }
                 }
-                else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
-                    auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
-                    if (!bindprop.get() || !*(bindprop.get())) {
-                        log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
+                else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
+                    string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
+                    if (bindprop.empty()) {
+                        log.error("SingleLogoutService element has no Binding attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
+                    handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
                 }
-                else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
-                    auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
-                    if (!bindprop.get() || !*(bindprop.get())) {
-                        log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
+                else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
+                    string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
+                    if (bindprop.empty()) {
+                        log.error("ManageNameIDService element has no Binding attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
+                    handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
                 }
                 else {
-                    auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                    if (!type.get() || !*(type.get())) {
-                        log.warn("Handler element has no type attribute, skipping it...");
+                    string t(XMLHelper::getAttrString(child, nullptr, _type));
+                    if (t.empty()) {
+                        log.error("Handler element has no type attribute, skipping it...");
                         child = XMLHelper::getNextSiblingElement(child);
                         continue;
                     }
-                    handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
+                    handler = conf.HandlerManager.newPlugin(t.c_str(), make_pair(child, getId()));
                 }
 
                 m_handlers.push_back(handler);
 
                 // Insert into location map.
-                location=handler->getString("Location");
+                location = handler->getString("Location");
                 if (location.first && *location.second == '/')
-                    m_handlerMap[location.second]=handler;
+                    m_handlerMap[location.second] = handler;
                 else if (location.first)
-                    m_handlerMap[string("/") + location.second]=handler;
-
+                    m_handlerMap[string("/") + location.second] = handler;
             }
             catch (exception& ex) {
                 log.error("caught exception processing handler element: %s", ex.what());
@@ -712,35 +763,43 @@ XMLApplication::XMLApplication(
         }
 
         // Notification.
-        DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
-        for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
+        DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
+        for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
             if (nlist->item(i)->getParentNode()->isSameNode(e)) {
-                const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
-                auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
-                if (loc.get() && *loc.get()) {
+                const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
+                string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
+                if (!loc.empty()) {
                     if (channel && *channel == chLatin_f)
-                        m_frontLogout.push_back(loc.get());
+                        m_frontLogout.push_back(loc);
                     else
-                        m_backLogout.push_back(loc.get());
+                        m_backLogout.push_back(loc);
                 }
             }
         }
 
 #ifndef SHIBSP_LITE
-        nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
-        for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
-            if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
-                m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
+        nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
+        if (nlist && nlist->getLength()) {
+            log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
+            for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
+                if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
+                    m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
+        }
 
         if (conf.isEnabled(SPConfig::Metadata)) {
-            child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
+            child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building MetadataProvider of type %s...",type.get());
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
                 try {
-                    auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
-                    mp->init();
-                    m_metadata = mp.release();
+                    if (!t.empty()) {
+                        log.info("building MetadataProvider of type %s...", t.c_str());
+                        auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(t.c_str(), child));
+                        mp->init();
+                        m_metadata = mp.release();
+                    }
+                    else {
+                        throw ConfigurationException("MetadataProvider element had no type attribute.");
+                    }
                 }
                 catch (exception& ex) {
                     log.crit("error building/initializing MetadataProvider: %s", ex.what());
@@ -749,50 +808,82 @@ XMLApplication::XMLApplication(
         }
 
         if (conf.isEnabled(SPConfig::Trust)) {
-            child = XMLHelper::getFirstChildElement(e,_TrustEngine);
+            child = XMLHelper::getFirstChildElement(e, _TrustEngine);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building TrustEngine of type %s...",type.get());
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
                 try {
-                    m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
+                    if (!t.empty()) {
+                        log.info("building TrustEngine of type %s...", t.c_str());
+                        m_trust = xmlConf.TrustEngineManager.newPlugin(t.c_str(), child);
+                    }
+                    else {
+                        throw ConfigurationException("TrustEngine element had no type attribute.");
+                    }
                 }
                 catch (exception& ex) {
                     log.crit("error building TrustEngine: %s", ex.what());
                 }
             }
+            else if (!m_base) {
+                log.info(
+                    "no TrustEngine specified, using default chain {%s, %s}",
+                    EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
+                    );
+                m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
+                ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
+                if (trustchain) {
+                    trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
+                    trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
+                }
+            }
         }
 
         if (conf.isEnabled(SPConfig::AttributeResolution)) {
-            child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
+            child = XMLHelper::getFirstChildElement(e, _AttributeExtractor);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building AttributeExtractor of type %s...",type.get());
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
                 try {
-                    m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
+                    if (!t.empty()) {
+                        log.info("building AttributeExtractor of type %s...", t.c_str());
+                        m_attrExtractor = conf.AttributeExtractorManager.newPlugin(t.c_str(), child);
+                    }
+                    else {
+                        throw ConfigurationException("AttributeExtractor element had no type attribute.");
+                    }
                 }
                 catch (exception& ex) {
                     log.crit("error building AttributeExtractor: %s", ex.what());
                 }
             }
 
-            child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
+            child = XMLHelper::getFirstChildElement(e, _AttributeFilter);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building AttributeFilter of type %s...",type.get());
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
                 try {
-                    m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
+                    if (!t.empty()) {
+                        log.info("building AttributeFilter of type %s...", t.c_str());
+                        m_attrFilter = conf.AttributeFilterManager.newPlugin(t.c_str(), child);
+                    }
+                    else {
+                        throw ConfigurationException("AttributeFilter element had no type attribute.");
+                    }
                 }
                 catch (exception& ex) {
                     log.crit("error building AttributeFilter: %s", ex.what());
                 }
             }
 
-            child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
+            child = XMLHelper::getFirstChildElement(e, _AttributeResolver);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building AttributeResolver of type %s...",type.get());
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
                 try {
-                    m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
+                    if (!t.empty()) {
+                        log.info("building AttributeResolver of type %s...", t.c_str());
+                        m_attrResolver = conf.AttributeResolverManager.newPlugin(t.c_str(), child);
+                    }
+                    else {
+                        throw ConfigurationException("AttributeResolver element had no type attribute.");
+                    }
                 }
                 catch (exception& ex) {
                     log.crit("error building AttributeResolver: %s", ex.what());
@@ -805,18 +896,20 @@ XMLApplication::XMLApplication(
                     Locker extlock(m_attrExtractor);
                     m_attrExtractor->getAttributeIds(unsetHeaders);
                 }
+                else if (m_base && m_base->m_attrExtractor) {
+                    Locker extlock(m_base->m_attrExtractor);
+                    m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
+                }
                 if (m_attrResolver) {
                     Locker reslock(m_attrResolver);
                     m_attrResolver->getAttributeIds(unsetHeaders);
                 }
-                if (unsetHeaders.empty()) {
-                    if (m_base)
-                        m_unsetHeaders.insert(m_unsetHeaders.end(), m_base->m_unsetHeaders.begin(), m_base->m_unsetHeaders.end());
-                    else
-                        m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
+                else if (m_base && m_base->m_attrResolver) {
+                    Locker extlock(m_base->m_attrResolver);
+                    m_base->m_attrResolver->getAttributeIds(unsetHeaders);
                 }
-                else {
-                    string transformedprefix("HTTP_");
+                if (!unsetHeaders.empty()) {
+                    string transformedprefix(m_attributePrefix.second);
                     const char* pch;
                     pair<bool,const char*> prefix = getString("metadataAttributePrefix");
                     if (prefix.first) {
@@ -833,19 +926,19 @@ XMLApplication::XMLApplication(
                             transformed += (isalnum(*pch) ? toupper(*pch) : '_');
                             pch++;
                         }
-                        m_unsetHeaders.push_back(pair<string,string>(*hdr, string("HTTP_") + transformed));
+                        m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
                         if (prefix.first)
-                            m_unsetHeaders.push_back(pair<string,string>(string(prefix.second) + *hdr, transformedprefix + transformed));
+                            m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
                     }
-                    m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
                 }
+                m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
             }
         }
 
         if (conf.isEnabled(SPConfig::Credentials)) {
             child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
             if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
+                auto_ptr_char type(child->getAttributeNS(nullptr,_type));
                 log.info("building CredentialResolver of type %s...",type.get());
                 try {
                     m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
@@ -860,9 +953,9 @@ XMLApplication::XMLApplication(
         child = XMLHelper::getFirstChildElement(e,RelyingParty);
         while (child) {
             auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
-            rp->load(child,NULL,this);
+            rp->load(child,nullptr,this);
             rp->setParent(this);
-            m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
+            m_partyMap[child->getAttributeNS(nullptr,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
             child = XMLHelper::getNextSiblingElement(child,RelyingParty);
         }
 #endif
@@ -900,28 +993,29 @@ void XMLApplication::cleanup()
     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
     m_handlers.clear();
 #ifndef SHIBSP_LITE
-#ifdef HAVE_GOOD_STL
     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
-#else
-    for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
-#endif
     m_partyMap.clear();
     delete m_credResolver;
-    m_credResolver = NULL;
+    m_credResolver = nullptr;
     delete m_attrResolver;
-    m_attrResolver = NULL;
+    m_attrResolver = nullptr;
     delete m_attrFilter;
-    m_attrFilter = NULL;
+    m_attrFilter = nullptr;
     delete m_attrExtractor;
-    m_attrExtractor = NULL;
+    m_attrExtractor = nullptr;
     delete m_trust;
-    m_trust = NULL;
+    m_trust = nullptr;
     delete m_metadata;
-    m_metadata = NULL;
+    m_metadata = nullptr;
 #endif
 }
 
-short XMLApplication::acceptNode(const DOMNode* node) const
+#ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
+short
+#else
+DOMNodeFilter::FilterAction
+#endif
+XMLApplication::acceptNode(const DOMNode* node) const
 {
     const XMLCh* name=node->getLocalName();
     if (XMLString::equals(name,ApplicationOverride) ||
@@ -953,7 +1047,6 @@ const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provi
     if (!provider)
         return this;
 
-#ifdef HAVE_GOOD_STL
     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
     if (i!=m_partyMap.end())
         return i->second;
@@ -966,19 +1059,6 @@ const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provi
         }
         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
     }
-#else
-    map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
-    for (; i!=m_partyMap.end(); i++) {
-        if (XMLString::equals(i->first,provider->getEntityID()))
-            return i->second;
-        const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
-        while (group) {
-            if (XMLString::equals(i->first,group->getName()))
-                return i->second;
-            group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
-        }
-    }
-#endif
     return this;
 }
 
@@ -987,17 +1067,9 @@ const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
     if (!entityID)
         return this;
 
-#ifdef HAVE_GOOD_STL
     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
     if (i!=m_partyMap.end())
         return i->second;
-#else
-    map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
-    for (; i!=m_partyMap.end(); i++) {
-        if (XMLString::equals(i->first,entityID))
-            return i->second;
-    }
-#endif
     return this;
 }
 
@@ -1038,7 +1110,7 @@ string XMLApplication::getNotificationURL(const char* resource, bool front, unsi
     // 2  handler   resource    handler
     // 3  resource  resource    handler
 
-    const char* path = NULL;
+    const char* path = nullptr;
 
     // Decide whether to use the handler or the resource for the "protocol"
     const char* prot;
@@ -1075,40 +1147,78 @@ string XMLApplication::getNotificationURL(const char* resource, bool front, unsi
     return notifyURL;
 }
 
+void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
+{
+    if (!m_attributePrefix.first.empty()) {
+        string temp = m_attributePrefix.first + rawname;
+        string temp2 = m_attributePrefix.second + (cginame + 5);
+        request.clearHeader(temp.c_str(), temp2.c_str());
+    }
+    else if (m_base) {
+        m_base->clearHeader(request, rawname, cginame);
+    }
+    else {
+        request.clearHeader(rawname, cginame);
+    }
+}
+
+void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
+{
+    if (!m_attributePrefix.first.empty()) {
+        string temp = m_attributePrefix.first + name;
+        request.setHeader(temp.c_str(), value);
+    }
+    else if (m_base) {
+        m_base->setHeader(request, name, value);
+    }
+    else {
+        request.setHeader(name, value);
+    }
+}
+
+string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
+{
+    if (!m_attributePrefix.first.empty()) {
+        string temp = m_attributePrefix.first + name;
+        return request.getSecureHeader(temp.c_str());
+    }
+    else if (m_base) {
+        return m_base->getSecureHeader(request,name);
+    }
+    else {
+        return request.getSecureHeader(name);
+    }
+}
+
 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
 {
     if (m_sessionInitDefault) return m_sessionInitDefault;
-    return m_base ? m_base->getDefaultSessionInitiator() : NULL;
+    return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
 }
 
 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
 {
     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
     if (i!=m_sessionInitMap.end()) return i->second;
-    return m_base ? m_base->getSessionInitiatorById(id) : NULL;
+    return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
 }
 
 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
 {
     if (m_acsDefault) return m_acsDefault;
-    return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
+    return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
 }
 
 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
 {
     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
     if (i!=m_acsIndexMap.end()) return i->second;
-    return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
+    return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
 }
 
 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
 {
-#ifdef HAVE_GOOD_STL
     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
-#else
-    auto_ptr_char temp(binding);
-    ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
-#endif
     if (i!=m_acsBindingMap.end())
         return i->second;
     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
@@ -1117,10 +1227,11 @@ const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBind
 const Handler* XMLApplication::getHandler(const char* path) const
 {
     string wrap(path);
+    wrap = wrap.substr(0,wrap.find(';'));
     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
     if (i!=m_handlerMap.end())
         return i->second;
-    return m_base ? m_base->getHandler(path) : NULL;
+    return m_base ? m_base->getHandler(path) : nullptr;
 }
 
 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
@@ -1134,7 +1245,12 @@ void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
     }
 }
 
-short XMLConfigImpl::acceptNode(const DOMNode* node) const
+#ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
+short
+#else
+DOMNodeFilter::FilterAction
+#endif
+XMLConfigImpl::acceptNode(const DOMNode* node) const
 {
     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
         return FILTER_ACCEPT;
@@ -1146,6 +1262,7 @@ short XMLConfigImpl::acceptNode(const DOMNode* node) const
         XMLString::equals(name,_RequestMapper) ||
         XMLString::equals(name,_ReplayCache) ||
         XMLString::equals(name,SecurityPolicies) ||
+        XMLString::equals(name,SecurityPolicyProvider) ||
         XMLString::equals(name,_SessionCache) ||
         XMLString::equals(name,Site) ||
         XMLString::equals(name,_StorageService) ||
@@ -1159,35 +1276,38 @@ short XMLConfigImpl::acceptNode(const DOMNode* node) const
 
 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
 {
-    const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
+    const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
     if (exts) {
-        exts=XMLHelper::getFirstChildElement(exts,Library);
+        exts = XMLHelper::getFirstChildElement(exts, Library);
         while (exts) {
-            auto_ptr_char path(exts->getAttributeNS(NULL,_path));
+            string path(XMLHelper::getAttrString(exts, nullptr, _path));
             try {
-                if (path.get()) {
-                    if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
+                if (!path.empty()) {
+                    if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
-                    log.debug("loaded %s extension library (%s)", label, path.get());
+                    log.debug("loaded %s extension library (%s)", label, path.c_str());
                 }
             }
             catch (exception& e) {
-                const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
-                if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
-                    log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
+                if (XMLHelper::getAttrBool(exts, false, _fatal)) {
+                    log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
                     throw;
                 }
                 else {
-                    log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
+                    log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
                 }
             }
-            exts=XMLHelper::getNextSiblingElement(exts,Library);
+            exts = XMLHelper::getNextSiblingElement(exts, Library);
         }
     }
 }
 
 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
-    : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
+    : m_requestMapper(nullptr),
+#ifndef SHIBSP_LITE
+        m_policy(nullptr),
+#endif
+        m_outer(outer), m_document(nullptr)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("XMLConfigImpl");
@@ -1199,22 +1319,31 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* o
         SAMLConfig& samlConf=SAMLConfig::getConfig();
 #endif
         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
-        const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
-        const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
+        const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
+        const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
 
-        // Initialize log4cpp manually in order to redirect log messages as soon as possible.
+        // Initialize logging manually in order to redirect log messages as soon as possible.
         if (conf.isEnabled(SPConfig::Logging)) {
-            const XMLCh* logconf=NULL;
+            string logconf;
             if (conf.isEnabled(SPConfig::OutOfProcess))
-                logconf=SHAR->getAttributeNS(NULL,logger);
+                logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
             else if (conf.isEnabled(SPConfig::InProcess))
-                logconf=SHIRE->getAttributeNS(NULL,logger);
-            if (!logconf || !*logconf)
-                logconf=e->getAttributeNS(NULL,logger);
-            if (logconf && *logconf) {
-                auto_ptr_char logpath(logconf);
-                log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
-                XMLToolingConfig::getConfig().log_config(logpath.get());
+                logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
+            if (logconf.empty())
+                logconf = XMLHelper::getAttrString(e, nullptr, logger);
+            if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
+                // No properties found, so default them.
+                if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
+                    logconf = "shibd.logger";
+                else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
+                    logconf = "native.logger";
+                else
+                    logconf = "shibboleth.logger";
+            }
+            if (!logconf.empty()) {
+                log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
+                if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
+                    log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
             }
 
 #ifndef SHIBSP_LITE
@@ -1223,11 +1352,24 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* o
 #endif
         }
 
+        // Re-log library versions now that logging is set up.
+        log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
+#ifndef SHIBSP_LITE
+        log.info(
+            "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
+            XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
+            );
+#else
+        log.info(
+            "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
+            XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
+            );
+#endif
+
         // First load any property sets.
-        load(e,NULL,this);
+        load(e,nullptr,this);
 
-        const DOMElement* child;
-        string plugtype;
+        DOMElement* child;
 
         // Much of the processing can only occur on the first instantiation.
         if (first) {
@@ -1236,6 +1378,24 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* o
             if (skew.first)
                 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
 
+            pair<bool,const char*> unsafe = getString("unsafeChars");
+            if (unsafe.first)
+                TemplateEngine::unsafe_chars = unsafe.second;
+
+            unsafe = getString("allowedSchemes");
+            if (unsafe.first) {
+                HTTPResponse::getAllowedSchemes().clear();
+                string schemes=unsafe.second;
+                unsigned int j_sch=0;
+                for (unsigned int i_sch=0;  i_sch < schemes.length();  i_sch++) {
+                    if (schemes.at(i_sch)==' ') {
+                        HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
+                        j_sch = i_sch + 1;
+                    }
+                }
+                HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
+            }
+
             // Extensions
             doExtensions(e, "global", log);
             if (conf.isEnabled(SPConfig::OutOfProcess))
@@ -1246,185 +1406,229 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* o
 
             // Instantiate the ListenerService and SessionCache objects.
             if (conf.isEnabled(SPConfig::Listener)) {
-                child=XMLHelper::getFirstChildElement(e,UnixListener);
+#ifdef WIN32
+                string plugtype(TCP_LISTENER_SERVICE);
+#else
+                string plugtype(UNIX_LISTENER_SERVICE);
+#endif
+                child = XMLHelper::getFirstChildElement(e, UnixListener);
                 if (child)
-                    plugtype=UNIX_LISTENER_SERVICE;
+                    plugtype = UNIX_LISTENER_SERVICE;
                 else {
-                    child=XMLHelper::getFirstChildElement(e,TCPListener);
+                    child = XMLHelper::getFirstChildElement(e, TCPListener);
                     if (child)
-                        plugtype=TCP_LISTENER_SERVICE;
+                        plugtype = TCP_LISTENER_SERVICE;
                     else {
-                        child=XMLHelper::getFirstChildElement(e,Listener);
+                        child = XMLHelper::getFirstChildElement(e, Listener);
                         if (child) {
-                            auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                            if (type.get())
-                                plugtype=type.get();
+                            auto_ptr_char type(child->getAttributeNS(nullptr, _type));
+                            if (type.get() && *type.get())
+                                plugtype = type.get();
                         }
                     }
                 }
-                if (child) {
-                    log.info("building ListenerService of type %s...", plugtype.c_str());
-                    m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
-                }
-                else {
-                    log.fatal("can't build ListenerService, missing conf:Listener element?");
-                    throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
-                }
+
+                log.info("building ListenerService of type %s...", plugtype.c_str());
+                m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
             }
 
 #ifndef SHIBSP_LITE
             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
-                m_outer->m_listener->regListener("set::RelayState", m_outer->m_listener);
-                m_outer->m_listener->regListener("get::RelayState", m_outer->m_listener);
+                m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
+                m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
+                m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
+                m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
             }
 #endif
 
             if (conf.isEnabled(SPConfig::Caching)) {
-                if (conf.isEnabled(SPConfig::OutOfProcess)) {
 #ifndef SHIBSP_LITE
+                if (conf.isEnabled(SPConfig::OutOfProcess)) {
                     // First build any StorageServices.
-                    child=XMLHelper::getFirstChildElement(e,_StorageService);
+                    child = XMLHelper::getFirstChildElement(e, _StorageService);
                     while (child) {
-                        auto_ptr_char id(child->getAttributeNS(NULL,_id));
-                        auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                        try {
-                            log.info("building StorageService (%s) of type %s...", id.get(), type.get());
-                            m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
-                        }
-                        catch (exception& ex) {
-                            log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
+                        string id(XMLHelper::getAttrString(child, nullptr, _id));
+                        string t(XMLHelper::getAttrString(child, nullptr, _type));
+                        if (!t.empty()) {
+                            try {
+                                log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
+                                m_outer->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
+                            }
+                            catch (exception& ex) {
+                                log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
+                            }
                         }
-                        child=XMLHelper::getNextSiblingElement(child,_StorageService);
+                        child = XMLHelper::getNextSiblingElement(child, _StorageService);
+                    }
+
+                    if (m_outer->m_storage.empty()) {
+                        log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
+                        m_outer->m_storage["id"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
                     }
 
                     // Replay cache.
-                    StorageService* replaySS=NULL;
-                    child=XMLHelper::getFirstChildElement(e,_ReplayCache);
+                    StorageService* replaySS = nullptr;
+                    child = XMLHelper::getFirstChildElement(e, _ReplayCache);
                     if (child) {
-                        auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
-                        if (ssid.get() && *ssid.get()) {
-                            if (m_outer->m_storage.count(ssid.get()))
-                                replaySS = m_outer->m_storage[ssid.get()];
-                            if (replaySS)
-                                log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
-                            else
-                                log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
+                        string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
+                        if (!ssid.empty()) {
+                            if (m_outer->m_storage.count(ssid)) {
+                                log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
+                                replaySS = m_outer->m_storage[ssid];
+                            }
+                            else {
+                                log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
+                                replaySS = m_outer->m_storage.begin()->second;
+                            }
+                        }
+                        else {
+                            log.info("no StorageService specified for ReplayCache, using arbitrary instance");
+                            replaySS = m_outer->m_storage.begin()->second;
                         }
-                        xmlConf.setReplayCache(new ReplayCache(replaySS));
                     }
                     else {
-                        log.warn("no ReplayCache built, missing conf:ReplayCache element?");
+                        log.info("no ReplayCache specified, using arbitrary StorageService instance");
+                        replaySS = m_outer->m_storage.begin()->second;
                     }
+                    xmlConf.setReplayCache(new ReplayCache(replaySS));
 
                     // ArtifactMap
-                    child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
+                    child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
                     if (child) {
-                        auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
-                        if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
-                            log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
-                            samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
+                        string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
+                        if (!ssid.empty()) {
+                            if (m_outer->m_storage.count(ssid)) {
+                                log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
+                                samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid]));
+                            }
+                            else {
+                                log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
+                                samlConf.setArtifactMap(new ArtifactMap(child));
+                            }
+                        }
+                        else {
+                            log.info("no StorageService specified, using in-memory ArtifactMap");
+                            samlConf.setArtifactMap(new ArtifactMap(child));
                         }
                     }
-                    if (samlConf.getArtifactMap()==NULL) {
-                        log.info("building in-memory ArtifactMap...");
+                    else {
+                        log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
                         samlConf.setArtifactMap(new ArtifactMap(child));
                     }
+                }   // end of out of process caching components
 #endif
-                }
-                child=XMLHelper::getFirstChildElement(e,_SessionCache);
+
+                child = XMLHelper::getFirstChildElement(e, _SessionCache);
                 if (child) {
-                    auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                    log.info("building SessionCache of type %s...",type.get());
-                    m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
+                    string t(XMLHelper::getAttrString(child, nullptr, _type));
+                    if (!t.empty()) {
+                        log.info("building SessionCache of type %s...", t.c_str());
+                        m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(t.c_str(), child);
+                    }
                 }
-                else {
-                    log.fatal("can't build SessionCache, missing conf:SessionCache element?");
-                    throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
+                if (!m_outer->m_sessionCache) {
+                    log.info("no SessionCache specified, using StorageService-backed instance");
+                    m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
                 }
             }
         } // end of first-time-only stuff
 
         // Back to the fully dynamic stuff...next up is the RequestMapper.
         if (conf.isEnabled(SPConfig::RequestMapping)) {
-            child=XMLHelper::getFirstChildElement(e,_RequestMapper);
-            if (child) {
-                auto_ptr_char type(child->getAttributeNS(NULL,_type));
-                log.info("building RequestMapper of type %s...",type.get());
-                m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
+            if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
+                string t(XMLHelper::getAttrString(child, nullptr, _type));
+                if (!t.empty()) {
+                    log.info("building RequestMapper of type %s...", t.c_str());
+                    m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
+                }
             }
-            else {
-                log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
-                throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
+            if (!m_requestMapper) {
+                log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
+                child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
+                DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
+                mapperDummy->setAttributeNS(nullptr, applicationId, _default);
+                child->appendChild(mapperDummy);
+                m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
             }
         }
 
 #ifndef SHIBSP_LITE
         // Load security policies.
-        child = XMLHelper::getLastChildElement(e,SecurityPolicies);
-        if (child) {
-            PolicyNodeFilter filter;
-            child = XMLHelper::getFirstChildElement(child,Policy);
-            while (child) {
-                auto_ptr_char id(child->getAttributeNS(NULL,_id));
-                pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
-                rules.first = NULL;
-                auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
-                settings->load(child, NULL, &filter);
-                rules.first = settings.release();
-
-                // Process Rule elements.
-                const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);
-                while (rule) {
-                    auto_ptr_char type(rule->getAttributeNS(NULL,_type));
-                    try {
-                        rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
-                    }
-                    catch (exception& ex) {
-                        log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
-                    }
-                    rule = XMLHelper::getNextSiblingElement(rule,Rule);
-                }
+        if (child = XMLHelper::getLastChildElement(e, SecurityPolicyProvider)) {
+            string t(XMLHelper::getAttrString(child, nullptr, _type));
+            if (!t.empty()) {
+                log.info("building SecurityPolicyProvider of type %s...", t.c_str());
+                m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
+            }
+            else {
+                throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
+            }
+        }
+        else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
+            // For backward compatibility, wrap in a plugin element.
+            DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, SecurityPolicyProvider);
+            polwrapper->appendChild(child);
+            log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
+            m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
+        }
+        else {
+            log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
+            throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
+        }
 
-                child = XMLHelper::getNextSiblingElement(child,Policy);
+        if (first) {
+#ifdef SHIBSP_XMLSEC_WHITELISTING
+            vector<xstring>::const_iterator alg;
+            if (!m_policy->getAlgorithmBlacklist().empty()) {
+                for (alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
+                    XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
+            }
+            else if (!m_policy->getAlgorithmWhitelist().empty()) {
+                for (alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
+                    XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
             }
+#else
+            log.fatal("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
+            throw ConfigurationException("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists.");
+#endif
         }
 
         // Process TransportOption elements.
-        child = XMLHelper::getLastChildElement(e,TransportOption);
+        child = XMLHelper::getLastChildElement(e, TransportOption);
         while (child) {
             if (child->hasChildNodes()) {
-                auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
-                auto_ptr_char option(child->getAttributeNS(NULL,_option));
+                string provider(XMLHelper::getAttrString(child, nullptr, _provider));
+                string option(XMLHelper::getAttrString(child, nullptr, _option));
                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
-                if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
-                    m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
+                if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
+                    m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
                 }
             }
-            child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
+            child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
         }
 #endif
 
-        // Load the default application. This actually has a fixed ID of "default". ;-)
-        child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
+        // Load the default application.
+        child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
         if (!child) {
             log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
             throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
         }
-        XMLApplication* defapp=new XMLApplication(m_outer,child);
-        m_appmap[defapp->getId()]=defapp;
+        XMLApplication* defapp = new XMLApplication(m_outer, child);
+        m_appmap[defapp->getId()] = defapp;
 
         // Load any overrides.
-        child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
+        child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
         while (child) {
-            auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
+            auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer, child, defapp));
             if (m_appmap.count(iapp->getId()))
                 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
             else {
                 const char* iappid=iapp->getId();
-                m_appmap[iappid]=iapp.release();
+                m_appmap[iappid] = iapp.release();
             }
 
-            child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
+            child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
         }
     }
     catch (exception&) {
@@ -1443,17 +1647,14 @@ void XMLConfigImpl::cleanup()
     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
     m_appmap.clear();
 #ifndef SHIBSP_LITE
-    for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
-        delete i->second.first;
-        for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
-    }
-    m_policyMap.clear();
+    delete m_policy;
+    m_policy = nullptr;
 #endif
     delete m_requestMapper;
-    m_requestMapper = NULL;
+    m_requestMapper = nullptr;
     if (m_document)
         m_document->release();
-    m_document = NULL;
+    m_document = nullptr;
 }
 
 #ifndef SHIBSP_LITE
@@ -1480,7 +1681,7 @@ void XMLConfig::receive(DDF& in, ostream& out)
         }
 
         // Repack for return to caller.
-        DDF ret=DDF(NULL).string(relayState.c_str());
+        DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
         DDFJanitor jret(ret);
         out << ret;
     }
@@ -1495,7 +1696,7 @@ void XMLConfig::receive(DDF& in, ostream& out)
         if (storage) {
             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
             rsKey = SAMLArtifact::toHex(rsKey);
-            storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
+            storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
         }
         else {
             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
@@ -1504,28 +1705,86 @@ void XMLConfig::receive(DDF& in, ostream& out)
         }
 
         // Repack for return to caller.
-        DDF ret=DDF(NULL).string(rsKey.c_str());
+        DDF ret=DDF(nullptr).string(rsKey.c_str());
+        DDFJanitor jret(ret);
+        out << ret;
+    }
+    else if (!strcmp(in.name(), "get::PostData")) {
+        const char* id = in["id"].string();
+        const char* key = in["key"].string();
+        if (!id || !key)
+            throw ListenerException("Required parameters missing for PostData recovery.");
+
+        string postData;
+        StorageService* storage = getStorageService(id);
+        if (storage) {
+            if (storage->readString("PostData",key,&postData) > 0) {
+                storage->deleteString("PostData",key);
+            }
+        }
+        else {
+            Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
+                "Storage-backed PostData with invalid StorageService ID (%s)", id
+                );
+        }
+        // If the data's empty, we'll send nothing back.
+        // If not, we don't need to round trip it, just send back the serialized DDF list.
+        if (postData.empty()) {
+            DDF ret(nullptr);
+            DDFJanitor jret(ret);
+            out << ret;
+        }
+        else {
+            out << postData;
+        }
+    }
+    else if (!strcmp(in.name(), "set::PostData")) {
+        const char* id = in["id"].string();
+        if (!id || !in["parameters"].islist())
+            throw ListenerException("Required parameters missing for PostData creation.");
+
+        string rsKey;
+        StorageService* storage = getStorageService(id);
+        if (storage) {
+            SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
+            rsKey = SAMLArtifact::toHex(rsKey);
+            ostringstream params;
+            params << in["parameters"];
+            storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
+        }
+        else {
+            Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
+                "Storage-backed PostData with invalid StorageService ID (%s)", id
+                );
+        }
+
+        // Repack for return to caller.
+        DDF ret=DDF(nullptr).string(rsKey.c_str());
         DDFJanitor jret(ret);
         out << ret;
     }
 }
 #endif
 
-pair<bool,DOMElement*> XMLConfig::load()
+pair<bool,DOMElement*> XMLConfig::background_load()
 {
     // Load from source using base class.
     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
 
     // If we own it, wrap it.
-    XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
+    XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
 
-    XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
+    XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
 
     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
     impl->setDocument(docjanitor.release());
 
+    // Perform the swap inside a lock.
+    if (m_lock)
+        m_lock->wrlock();
+    SharedLock locker(m_lock, false);
     delete m_impl;
     m_impl = impl;
 
-    return make_pair(false,(DOMElement*)NULL);
+    return make_pair(false,(DOMElement*)nullptr);
 }