Move Shib constants to new lib, fixed symbol conflicts.
[shibboleth/cpp-sp.git] / shib-target / shib-ini.cpp
index 1519cc9..3e7244b 100644 (file)
 
 #include "internal.h"
 
-#include <shib/shib-threads.h>
+#include <shibsp/DOMPropertySet.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/SPConstants.h>
 #include <log4cpp/Category.hh>
 #include <log4cpp/PropertyConfigurator.hh>
-
+#include <algorithm>
 #include <sys/types.h>
 #include <sys/stat.h>
 
-using namespace std;
-using namespace saml;
-using namespace shibboleth;
+using namespace shibsp;
 using namespace shibtarget;
+using namespace shibboleth;
+using namespace saml;
 using namespace log4cpp;
+using namespace std;
+
+using xmltooling::TrustEngine;
+using opensaml::saml2md::MetadataProvider;
 
 namespace shibtarget {
 
     // Application configuration wrapper
-    class XMLApplication : public virtual IApplication, public XMLPropertySet, public DOMNodeFilter
+    class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
     {
     public:
         XMLApplication(const IConfig*, const Iterator<ICredentials*>& creds, const DOMElement* e, const XMLApplication* base=NULL);
         ~XMLApplication() { cleanup(); }
     
-        // IPropertySet
+        // PropertySet
         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
-        const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
+        const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
 
         // IApplication
         const char* getId() const {return getString("id").second;}
@@ -60,16 +66,27 @@ namespace shibtarget {
         Iterator<IMetadata*> getMetadataProviders() const;
         Iterator<ITrust*> getTrustProviders() const;
         Iterator<const XMLCh*> getAudiences() const;
-        const IPropertySet* getCredentialUse(const IEntityDescriptor* provider) const;
+        const PropertySet* getCredentialUse(const IEntityDescriptor* provider) const;
+
+        const MetadataProvider* getMetadataProvider() const;
+        const TrustEngine* getTrustEngine() const;
+        
         const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
         const SAMLBinding* getBinding(const XMLCh* binding) const
             {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
         SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
-        const IPropertySet* getDefaultSessionInitiator() const;
-        const IPropertySet* getSessionInitiatorById(const char* id) const;
-        const IPropertySet* getDefaultAssertionConsumerService() const;
-        const IPropertySet* getAssertionConsumerServiceByIndex(unsigned short index) const;
-        const IPropertySet* getHandlerConfig(const char* path) const;
+        void validateToken(
+            SAMLAssertion* token,
+            time_t t=0,
+            const IRoleDescriptor* role=NULL,
+            const Iterator<ITrust*>& trusts=EMPTY(ITrust*)
+            ) const;
+        const IHandler* getDefaultSessionInitiator() const;
+        const IHandler* getSessionInitiatorById(const char* id) const;
+        const IHandler* getDefaultAssertionConsumerService() const;
+        const IHandler* getAssertionConsumerServiceByIndex(unsigned short index) const;
+        Iterator<const IHandler*> getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
+        const IHandler* getHandler(const char* path) const;
         
         // Provides filter to exclude special config elements.
         short acceptNode(const DOMNode* node) const;
@@ -83,26 +100,51 @@ namespace shibtarget {
         vector<IAAP*> m_aaps;
         vector<IMetadata*> m_metadatas;
         vector<ITrust*> m_trusts;
+        MetadataProvider* m_metadata;
+        TrustEngine* m_trust;
         vector<const XMLCh*> m_audiences;
         ShibBrowserProfile* m_profile;
         SAMLBinding* m_binding;
         ShibHTTPHook* m_bindingHook;
-        map<string,XMLPropertySet*> m_handlerMap;
-        map<unsigned int,const IPropertySet*> m_acsMap;
-        const IPropertySet* m_acsDefault;
-        map<string,const IPropertySet*> m_sessionInitMap;
-        const IPropertySet* m_sessionInitDefault;
-        XMLPropertySet* m_credDefault;
+
+        // vectors manage object life for handlers and their property sets
+        vector<IHandler*> m_handlers;
+        vector<PropertySet*> m_handlerProps;
+
+        // maps location (path info) to applicable handlers
+        map<string,const IHandler*> m_handlerMap;
+
+        // maps unique indexes to consumer services
+        map<unsigned int,const IHandler*> m_acsIndexMap;
+        
+        // pointer to default consumer service
+        const IHandler* m_acsDefault;
+
+        // maps binding strings to supporting consumer service(s)
+#ifdef HAVE_GOOD_STL
+        typedef map<xstring,vector<const IHandler*> > ACSBindingMap;
+#else
+        typedef map<string,vector<const IHandler*> > ACSBindingMap;
+#endif
+        ACSBindingMap m_acsBindingMap;
+
+        // maps unique ID strings to session initiators
+        map<string,const IHandler*> m_sessionInitMap;
+
+        // pointer to default session initiator
+        const IHandler* m_sessionInitDefault;
+
+        DOMPropertySet* m_credDefault;
 #ifdef HAVE_GOOD_STL
-        map<xstring,XMLPropertySet*> m_credMap;
+        map<xstring,PropertySet*> m_credMap;
 #else
-        map<const XMLCh*,XMLPropertySet*> m_credMap;
+        map<const XMLCh*,PropertySet*> m_credMap;
 #endif
     };
 
     // Top-level configuration implementation
     class XMLConfig;
-    class XMLConfigImpl : public ReloadableXMLFileImpl, public XMLPropertySet, public DOMNodeFilter
+    class XMLConfigImpl : public ReloadableXMLFileImpl, public DOMPropertySet, public DOMNodeFilter
     {
     public:
         XMLConfigImpl(const char* pathname, bool first, const XMLConfig* outer)
@@ -128,19 +170,30 @@ namespace shibtarget {
     {
     public:
         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {}
-        ~XMLConfig() {delete m_listener; delete m_sessionCache; delete m_replayCache;}
+        ~XMLConfig() {
+            delete m_impl;
+            m_impl=NULL;
+            delete m_sessionCache;
+            m_sessionCache=NULL;
+            delete m_replayCache;
+            m_replayCache=NULL;
+            delete m_listener;
+            m_listener=NULL;
+        }
 
-        // IPropertySet
+        void init() { getImplementation(); }
+
+        // PropertySet
         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getBool(name,ns);}
         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getString(name,ns);}
         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getXMLString(name,ns);}
         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getUnsignedInt(name,ns);}
         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getInt(name,ns);}
-        const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return static_cast<XMLConfigImpl*>(m_impl)->getPropertySet(name,ns);}
+        const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return static_cast<XMLConfigImpl*>(m_impl)->getPropertySet(name,ns);}
         const DOMElement* getElement() const {return static_cast<XMLConfigImpl*>(m_impl)->getElement();}
 
         // IConfig
-        const IListener* getListener() const {return m_listener;}
+        ListenerService* getListener() const {return m_listener;}
         ISessionCache* getSessionCache() const {return m_sessionCache;}
         IReplayCache* getReplayCache() const {return m_replayCache;}
         IRequestMapper* getRequestMapper() const {return static_cast<XMLConfigImpl*>(m_impl)->m_requestMapper;}
@@ -156,7 +209,7 @@ namespace shibtarget {
 
     private:
         friend class XMLConfigImpl;
-        mutable IListener* m_listener;
+        mutable ListenerService* m_listener;
         mutable ISessionCache* m_sessionCache;
         mutable IReplayCache* m_replayCache;
     };
@@ -164,190 +217,7 @@ namespace shibtarget {
 
 IConfig* STConfig::ShibTargetConfigFactory(const DOMElement* e)
 {
-    auto_ptr<XMLConfig> ret(new XMLConfig(e));
-    ret->getImplementation();
-    return ret.release();
-}
-
-XMLPropertySet::~XMLPropertySet()
-{
-    for (map<string,pair<char*,const XMLCh*> >::iterator i=m_map.begin(); i!=m_map.end(); i++)
-        XMLString::release(&(i->second.first));
-    for (map<string,IPropertySet*>::iterator j=m_nested.begin(); j!=m_nested.end(); j++)
-        delete j->second;
-}
-
-void XMLPropertySet::load(
-    const DOMElement* e,
-    Category& log,
-    DOMNodeFilter* filter,
-    const std::map<std::string,std::string>* remapper
-    )
-{
-#ifdef _DEBUG
-    saml::NDC ndc("load");
-#endif
-    m_root=e;
-
-    // Process each attribute as a property.
-    DOMNamedNodeMap* attrs=m_root->getAttributes();
-    for (XMLSize_t i=0; i<attrs->getLength(); i++) {
-        DOMNode* a=attrs->item(i);
-        if (!XMLString::compareString(a->getNamespaceURI(),saml::XML::XMLNS_NS))
-            continue;
-        char* val=XMLString::transcode(a->getNodeValue());
-        if (val && *val) {
-            auto_ptr_char ns(a->getNamespaceURI());
-            auto_ptr_char name(a->getLocalName());
-            const char* realname=name.get();
-            if (remapper) {
-                map<string,string>::const_iterator remap=remapper->find(realname);
-                if (remap!=remapper->end()) {
-                    log.debug("remapping property (%s) to (%s)",realname,remap->second.c_str());
-                    realname=remap->second.c_str();
-                }
-            }
-            if (ns.get()) {
-                m_map[string("{") + ns.get() + '}' + realname]=pair<char*,const XMLCh*>(val,a->getNodeValue());
-                log.debug("added property {%s}%s (%s)",ns.get(),realname,val);
-            }
-            else {
-                m_map[realname]=pair<char*,const XMLCh*>(val,a->getNodeValue());
-                log.debug("added property %s (%s)",realname,val);
-            }
-        }
-    }
-    
-    // Process non-excluded elements as nested sets.
-    DOMTreeWalker* walker=
-        static_cast<DOMDocumentTraversal*>(
-            m_root->getOwnerDocument())->createTreeWalker(const_cast<DOMElement*>(m_root),DOMNodeFilter::SHOW_ELEMENT,filter,false
-            );
-    e=static_cast<DOMElement*>(walker->firstChild());
-    while (e) {
-        auto_ptr_char ns(e->getNamespaceURI());
-        auto_ptr_char name(e->getLocalName());
-        const char* realname=name.get();
-        if (remapper) {
-            map<string,string>::const_iterator remap=remapper->find(realname);
-            if (remap!=remapper->end()) {
-                log.debug("remapping property set (%s) to (%s)",realname,remap->second.c_str());
-                realname=remap->second.c_str();
-            }
-        }
-        string key;
-        if (ns.get())
-            key=string("{") + ns.get() + '}' + realname;
-        else
-            key=realname;
-        if (m_nested.find(key)!=m_nested.end())
-            log.warn("load() skipping duplicate property set: %s",key.c_str());
-        else {
-            XMLPropertySet* set=new XMLPropertySet();
-            set->load(e,log,filter,remapper);
-            m_nested[key]=set;
-            log.debug("added nested property set: %s",key.c_str());
-        }
-        e=static_cast<DOMElement*>(walker->nextSibling());
-    }
-    walker->release();
-}
-
-pair<bool,bool> XMLPropertySet::getBool(const char* name, const char* ns) const
-{
-    pair<bool,bool> ret=pair<bool,bool>(false,false);
-    map<string,pair<char*,const XMLCh*> >::const_iterator i;
-
-    if (ns)
-        i=m_map.find(string("{") + ns + '}' + name);
-    else
-        i=m_map.find(name);
-
-    if (i!=m_map.end()) {
-        ret.first=true;
-        ret.second=(!strcmp(i->second.first,"true") || !strcmp(i->second.first,"1"));
-    }
-    return ret;
-}
-
-pair<bool,const char*> XMLPropertySet::getString(const char* name, const char* ns) const
-{
-    pair<bool,const char*> ret=pair<bool,const char*>(false,NULL);
-    map<string,pair<char*,const XMLCh*> >::const_iterator i;
-
-    if (ns)
-        i=m_map.find(string("{") + ns + '}' + name);
-    else
-        i=m_map.find(name);
-
-    if (i!=m_map.end()) {
-        ret.first=true;
-        ret.second=i->second.first;
-    }
-    return ret;
-}
-
-pair<bool,const XMLCh*> XMLPropertySet::getXMLString(const char* name, const char* ns) const
-{
-    pair<bool,const XMLCh*> ret=pair<bool,const XMLCh*>(false,NULL);
-    map<string,pair<char*,const XMLCh*> >::const_iterator i;
-
-    if (ns)
-        i=m_map.find(string("{") + ns + '}' + name);
-    else
-        i=m_map.find(name);
-
-    if (i!=m_map.end()) {
-        ret.first=true;
-        ret.second=i->second.second;
-    }
-    return ret;
-}
-
-pair<bool,unsigned int> XMLPropertySet::getUnsignedInt(const char* name, const char* ns) const
-{
-    pair<bool,unsigned int> ret=pair<bool,unsigned int>(false,0);
-    map<string,pair<char*,const XMLCh*> >::const_iterator i;
-
-    if (ns)
-        i=m_map.find(string("{") + ns + '}' + name);
-    else
-        i=m_map.find(name);
-
-    if (i!=m_map.end()) {
-        ret.first=true;
-        ret.second=strtol(i->second.first,NULL,10);
-    }
-    return ret;
-}
-
-pair<bool,int> XMLPropertySet::getInt(const char* name, const char* ns) const
-{
-    pair<bool,int> ret=pair<bool,int>(false,0);
-    map<string,pair<char*,const XMLCh*> >::const_iterator i;
-
-    if (ns)
-        i=m_map.find(string("{") + ns + '}' + name);
-    else
-        i=m_map.find(name);
-
-    if (i!=m_map.end()) {
-        ret.first=true;
-        ret.second=atoi(i->second.first);
-    }
-    return ret;
-}
-
-const IPropertySet* XMLPropertySet::getPropertySet(const char* name, const char* ns) const
-{
-    map<string,IPropertySet*>::const_iterator i;
-
-    if (ns)
-        i=m_nested.find(string("{") + ns + '}' + name);
-    else
-        i=m_nested.find(name);
-
-    return (i!=m_nested.end()) ? i->second : NULL;
+    return new XMLConfig(e);
 }
 
 XMLApplication::XMLApplication(
@@ -355,11 +225,11 @@ XMLApplication::XMLApplication(
     const Iterator<ICredentials*>& creds,
     const DOMElement* e,
     const XMLApplication* base
-    ) : m_ini(ini), m_base(base), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
+    ) : m_ini(ini), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
         m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
 {
 #ifdef _DEBUG
-    saml::NDC ndc("XMLApplication");
+    NDC ndc("XMLApplication");
 #endif
     Category& log=Category::getInstance("shibtarget.XMLApplication");
 
@@ -370,7 +240,7 @@ XMLApplication::XMLApplication(
         root_remap["shireURL"]="handlerURL";
         root_remap["shireSSL"]="handlerSSL";
         load(e,log,this,&root_remap);
-        const IPropertySet* propcheck=getPropertySet("Errors");
+        const PropertySet* propcheck=getPropertySet("Errors");
         if (propcheck && !propcheck->getString("session").first)
             throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
         propcheck=getPropertySet("Sessions");
@@ -381,51 +251,133 @@ XMLApplication::XMLApplication(
         m_hash+=getString("providerId").second;
         m_hash=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(m_hash.c_str()));
 
-        ShibTargetConfig& conf=ShibTargetConfig::getConfig();
+        SPConfig& conf=SPConfig::getConfig();
         SAMLConfig& shibConf=SAMLConfig::getConfig();
 
-        if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
-            // Process handlers.
-            bool hardACS=false, hardSessionInit=false;
-            DOMElement* handler=saml::XML::getFirstChildElement(propcheck->getElement());
-            while (handler) {
-                XMLPropertySet* hprops=new XMLPropertySet();
+        // Process handlers.
+        bool hardACS=false, hardSessionInit=false;
+        DOMElement* handler=saml::XML::getFirstChildElement(propcheck->getElement());
+        while (handler) {
+            // A handler is split across a property set and the plugin itself, which is based on the Binding property.
+            // We build both objects first and then insert them into various structures for lookup.
+            IHandler* hobj=NULL;
+            DOMPropertySet* hprops=new DOMPropertySet();
+            try {
                 hprops->load(handler,log,this); // filter irrelevant for now, no embedded elements expected
-                m_handlerMap[hprops->getString("Location").second]=hprops;
+                const char* bindprop=hprops->getString("Binding").second;
+                if (!bindprop)
+                    throw ConfigurationException("Handler element has no Binding attribute, skipping it...");
+                IPlugIn* hplug=shibConf.getPlugMgr().newPlugin(bindprop,handler);
+                hobj=dynamic_cast<IHandler*>(hplug);
+                if (!hobj) {
+                    delete hplug;
+                    throw UnsupportedProfileException(
+                        "Plugin for binding ($1) does not implement IHandler interface.",params(1,bindprop)
+                        );
+                }
+            }
+            catch (SAMLException& ex) {
+                // If we get here, the handler's not built, so dispose of the property set.
+                log.error("caught exception processing a handler element: %s",ex.what());
+                delete hprops;
+                hprops=NULL;
+            }
+            
+            const char* location=hprops ? hprops->getString("Location").second : NULL;
+            if (!location) {
+                delete hprops;
+                hprops=NULL;
+                handler=saml::XML::getNextSiblingElement(handler);
+                continue;
+            }
+            
+            // Save off the objects after giving the property set to the handler for its use.
+            hobj->setProperties(hprops);
+            m_handlers.push_back(hobj);
+            m_handlerProps.push_back(hprops);
+
+            // Insert into location map.
+            if (*location == '/')
+                m_handlerMap[location]=hobj;
+            else
+                m_handlerMap[string("/") + location]=hobj;
+
+            // If it's an ACS or SI, handle index/id mappings and defaulting.
+            if (saml::XML::isElementNamed(handler,shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
+                // Map it.
+#ifdef HAVE_GOOD_STL
+                const XMLCh* binding=hprops->getXMLString("Binding").second;
+#else
+                const char* binding=hprops->getString("Binding").second;
+#endif
+                if (m_acsBindingMap.count(binding)==0)
+                    m_acsBindingMap[binding]=vector<const IHandler*>(1,hobj);
+                else
+                    m_acsBindingMap[binding].push_back(hobj);
+                m_acsIndexMap[hprops->getUnsignedInt("index").second]=hobj;
                 
-                // If it's an ACS or SI, handle lookup mappings and defaulting.
-                if (saml::XML::isElementNamed(handler,shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
-                    m_acsMap[hprops->getUnsignedInt("index").second]=hprops;
-                    if (!hardACS) {
-                        pair<bool,bool> defprop=hprops->getBool("isDefault");
-                        if (defprop.first) {
-                            if (defprop.second) {
-                                hardACS=true;
-                                m_acsDefault=hprops;
-                            }
+                if (!hardACS) {
+                    pair<bool,bool> defprop=hprops->getBool("isDefault");
+                    if (defprop.first) {
+                        if (defprop.second) {
+                            hardACS=true;
+                            m_acsDefault=hobj;
                         }
-                        else if (!m_acsDefault)
-                            m_acsDefault=hprops;
                     }
+                    else if (!m_acsDefault)
+                        m_acsDefault=hobj;
                 }
-                else if (saml::XML::isElementNamed(handler,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
-                    pair<bool,const char*> si_id=hprops->getString("id");
-                    if (si_id.first && si_id.second)
-                        m_sessionInitMap[si_id.second]=hprops;
-                    if (!hardSessionInit) {
-                        pair<bool,bool> defprop=hprops->getBool("isDefault");
-                        if (defprop.first) {
-                            if (defprop.second) {
-                                hardSessionInit=true;
-                                m_sessionInitDefault=hprops;
-                            }
+            }
+            else if (saml::XML::isElementNamed(handler,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
+                pair<bool,const char*> si_id=hprops->getString("id");
+                if (si_id.first && si_id.second)
+                    m_sessionInitMap[si_id.second]=hobj;
+                if (!hardSessionInit) {
+                    pair<bool,bool> defprop=hprops->getBool("isDefault");
+                    if (defprop.first) {
+                        if (defprop.second) {
+                            hardSessionInit=true;
+                            m_sessionInitDefault=hobj;
                         }
-                        else if (!m_sessionInitDefault)
-                            m_sessionInitDefault=hprops;
                     }
+                    else if (!m_sessionInitDefault)
+                        m_sessionInitDefault=hobj;
                 }
-                handler=saml::XML::getNextSiblingElement(handler);
             }
+            handler=saml::XML::getNextSiblingElement(handler);
+        }
+
+        // If no handlers defined at the root, assume a legacy configuration.
+        if (!m_base && m_handlers.empty()) {
+            // A legacy config installs a SAML POST handler at the root handler location.
+            // We use the Sessions element itself as the PropertySet.
+
+            auto_ptr_char b1(shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI);
+            IPlugIn* hplug=shibConf.getPlugMgr().newPlugin(b1.get(),propcheck->getElement());
+            IHandler* h1=dynamic_cast<IHandler*>(hplug);
+            if (!h1) {
+                delete hplug;
+                throw UnsupportedProfileException(
+                    "Plugin for binding ($1) does not implement IHandler interface.",params(1,b1.get())
+                    );
+            }
+            h1->setProperties(propcheck);
+            m_handlers.push_back(h1);
+            m_sessionInitDefault=h1;
+
+            auto_ptr_char b2(SAMLBrowserProfile::BROWSER_POST);
+            hplug=shibConf.getPlugMgr().newPlugin(b2.get(),propcheck->getElement());
+            IHandler* h2=dynamic_cast<IHandler*>(hplug);
+            if (!h2) {
+                delete hplug;
+                throw UnsupportedProfileException(
+                    "Plugin for binding ($1) does not implement IHandler interface.",params(1,b2.get())
+                    );
+            }
+            h2->setProperties(propcheck);
+            m_handlers.push_back(h2);
+            m_handlerMap[""] = h2;
+            m_acsDefault=h2;
         }
         
         // Process general configuration elements.
@@ -443,7 +395,7 @@ XMLApplication::XMLApplication(
         // Always include our own providerId as an audience.
         m_audiences.push_back(getXMLString("providerId").second);
 
-        if (conf.isEnabled(ShibTargetConfig::AAP)) {
+        if (conf.isEnabled(SPConfig::AAP)) {
             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(AAPProvider));
             for (i=0; nlist && i<nlist->getLength(); i++) {
                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
@@ -466,7 +418,7 @@ XMLApplication::XMLApplication(
             }
         }
 
-        if (conf.isEnabled(ShibTargetConfig::Metadata)) {
+        if (conf.isEnabled(SPConfig::Metadata)) {
             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MetadataProvider));
             for (i=0; nlist && i<nlist->getLength(); i++) {
                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
@@ -509,7 +461,9 @@ XMLApplication::XMLApplication(
             }
         }
 
-        if (conf.isEnabled(ShibTargetConfig::Trust)) {
+        if (conf.isEnabled(SPConfig::Trust)) {
+            // First build the old plugins.
+            // TODO: remove this later
             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TrustProvider));
             for (i=0; nlist && i<nlist->getLength(); i++) {
                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
@@ -535,20 +489,21 @@ XMLApplication::XMLApplication(
         // Finally, load credential mappings.
         const DOMElement* cu=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialUse));
         if (cu) {
-            m_credDefault=new XMLPropertySet();
+            m_credDefault=new DOMPropertySet();
             m_credDefault->load(cu,log,this);
             cu=saml::XML::getFirstChildElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
             while (cu) {
-                XMLPropertySet* rp=new XMLPropertySet();
+                DOMPropertySet* rp=new DOMPropertySet();
                 rp->load(cu,log,this);
                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=rp;
                 cu=saml::XML::getNextSiblingElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
             }
         }
         
-        if (conf.isEnabled(ShibTargetConfig::Caching)) {
+        if (conf.isEnabled(SPConfig::OutOfProcess)) {
             // Really finally, build local browser profile and binding objects.
             m_profile=new ShibBrowserProfile(
+                this,
                 getMetadataProviders(),
                 getTrustProviders()
                 );
@@ -584,33 +539,18 @@ void XMLApplication::cleanup()
     delete m_bindingHook;
     delete m_binding;
     delete m_profile;
-    map<string,XMLPropertySet*>::iterator h=m_handlerMap.begin();
-    while (h!=m_handlerMap.end()) {
-        delete h->second;
-        h++;
-    }
+    for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<IHandler>());
+        
     delete m_credDefault;
 #ifdef HAVE_GOOD_STL
-    map<xstring,XMLPropertySet*>::iterator c=m_credMap.begin();
+    for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xstring,PropertySet>());
 #else
-    map<const XMLCh*,XMLPropertySet*>::iterator c=m_credMap.begin();
+    for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
 #endif
-    while (c!=m_credMap.end()) {
-        delete c->second;
-        c++;
-    }
-    Iterator<SAMLAttributeDesignator*> i(m_designators);
-    while (i.hasNext())
-        delete i.next();
-    Iterator<IAAP*> j(m_aaps);
-    while (j.hasNext())
-        delete j.next();
-    Iterator<IMetadata*> k(m_metadatas);
-    while (k.hasNext())
-        delete k.next();
-    Iterator<ITrust*> l(m_trusts);
-    while (l.hasNext())
-        delete l.next();
+    for_each(m_designators.begin(),m_designators.end(),xmltooling::cleanup<SAMLAttributeDesignator>());
+    for_each(m_aaps.begin(),m_aaps.end(),xmltooling::cleanup<IAAP>());
+    for_each(m_metadatas.begin(),m_metadatas.end(),xmltooling::cleanup<IMetadata>());
+    for_each(m_trusts.begin(),m_trusts.end(),xmltooling::cleanup<ITrust>());
 }
 
 short XMLApplication::acceptNode(const DOMNode* node) const
@@ -638,7 +578,7 @@ short XMLApplication::acceptNode(const DOMNode* node) const
 
 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
 {
-    pair<bool,bool> ret=XMLPropertySet::getBool(name,ns);
+    pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
     if (ret.first)
         return ret;
     return m_base ? m_base->getBool(name,ns) : ret;
@@ -646,7 +586,7 @@ pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
 
 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
 {
-    pair<bool,const char*> ret=XMLPropertySet::getString(name,ns);
+    pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
     if (ret.first)
         return ret;
     return m_base ? m_base->getString(name,ns) : ret;
@@ -654,7 +594,7 @@ pair<bool,const char*> XMLApplication::getString(const char* name, const char* n
 
 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
 {
-    pair<bool,const XMLCh*> ret=XMLPropertySet::getXMLString(name,ns);
+    pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
     if (ret.first)
         return ret;
     return m_base ? m_base->getXMLString(name,ns) : ret;
@@ -662,7 +602,7 @@ pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const cha
 
 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
 {
-    pair<bool,unsigned int> ret=XMLPropertySet::getUnsignedInt(name,ns);
+    pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
     if (ret.first)
         return ret;
     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
@@ -670,15 +610,15 @@ pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const c
 
 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
 {
-    pair<bool,int> ret=XMLPropertySet::getInt(name,ns);
+    pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
     if (ret.first)
         return ret;
     return m_base ? m_base->getInt(name,ns) : ret;
 }
 
-const IPropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
+const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
 {
-    const IPropertySet* ret=XMLPropertySet::getPropertySet(name,ns);
+    const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
     if (ret || !m_base)
         return ret;
     return m_base->getPropertySet(name,ns);
@@ -711,13 +651,13 @@ Iterator<const XMLCh*> XMLApplication::getAudiences() const
     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
 }
 
-const IPropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
+const PropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
 {
     if (!m_credDefault && m_base)
         return m_base->getCredentialUse(provider);
         
 #ifdef HAVE_GOOD_STL
-    map<xstring,XMLPropertySet*>::const_iterator i=m_credMap.find(provider->getId());
+    map<xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getId());
     if (i!=m_credMap.end())
         return i->second;
     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
@@ -730,7 +670,7 @@ const IPropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* pr
         group=group->getEntitiesDescriptor();
     }
 #else
-    map<const XMLCh*,XMLPropertySet*>::const_iterator i=m_credMap.begin();
+    map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
     for (; i!=m_credMap.end(); i++) {
         if (!XMLString::compareString(i->first,provider->getId()))
             return i->second;
@@ -745,39 +685,114 @@ const IPropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* pr
     return m_credDefault;
 }
 
-const IPropertySet* XMLApplication::getDefaultSessionInitiator() const
+const MetadataProvider* XMLApplication::getMetadataProvider() const
+{
+    return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
+}
+
+const TrustEngine* XMLApplication::getTrustEngine() const
+{
+    return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
+}
+
+void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const IRoleDescriptor* role, const Iterator<ITrust*>& trusts) const
+{
+#ifdef _DEBUG
+    saml::NDC ndc("validateToken");
+#endif
+    Category& log=Category::getInstance("shibtarget.XMLApplication");
+
+    // First we verify the time conditions, using the specified timestamp, if non-zero.
+    SAMLConfig& config=SAMLConfig::getConfig();
+    if (ts>0) {
+        const SAMLDateTime* notBefore=token->getNotBefore();
+        if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
+            throw ExpiredAssertionException("Assertion is not yet valid.");
+        const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
+        if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
+            throw ExpiredAssertionException("Assertion is no longer valid.");
+    }
+
+    // Now we process conditions. Only audience restrictions at the moment.
+    Iterator<SAMLCondition*> conditions=token->getConditions();
+    while (conditions.hasNext()) {
+        SAMLCondition* cond=conditions.next();
+        const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
+        if (!ac) {
+            ostringstream os;
+            os << *cond;
+            log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
+            throw UnsupportedExtensionException("Assertion contains an unrecognized condition.");
+        }
+        else if (!ac->eval(getAudiences())) {
+            ostringstream os;
+            os << *ac;
+            log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
+            throw UnsupportedProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
+        }
+    }
+
+    if (!role) {
+        log.warn("no metadata provided, so no signature validation was performed");
+        return;
+    }
+
+    const PropertySet* credUse=getCredentialUse(role->getEntityDescriptor());
+    pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
+    Trust t(trusts);
+
+    if (token->isSigned() && !t.validate(*token,role))
+        throw TrustException("Assertion signature did not validate.");
+    else if (signedAssertions.first && signedAssertions.second)
+        throw TrustException("Assertion was unsigned, violating policy based on the issuer.");
+}
+
+const IHandler* XMLApplication::getDefaultSessionInitiator() const
 {
     if (m_sessionInitDefault) return m_sessionInitDefault;
     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
 }
 
-const IPropertySet* XMLApplication::getSessionInitiatorById(const char* id) const
+const IHandler* XMLApplication::getSessionInitiatorById(const char* id) const
 {
-    map<string,const IPropertySet*>::const_iterator i=m_sessionInitMap.find(id);
+    map<string,const IHandler*>::const_iterator i=m_sessionInitMap.find(id);
     if (i!=m_sessionInitMap.end()) return i->second;
     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
 }
 
-const IPropertySet* XMLApplication::getDefaultAssertionConsumerService() const
+const IHandler* XMLApplication::getDefaultAssertionConsumerService() const
 {
     if (m_acsDefault) return m_acsDefault;
     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
 }
 
-const IPropertySet* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
+const IHandler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
 {
-    map<unsigned int,const IPropertySet*>::const_iterator i=m_acsMap.find(index);
-    if (i!=m_acsMap.end()) return i->second;
+    map<unsigned int,const IHandler*>::const_iterator i=m_acsIndexMap.find(index);
+    if (i!=m_acsIndexMap.end()) return i->second;
     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
 }
 
-const IPropertySet* XMLApplication::getHandlerConfig(const char* path) const
+Iterator<const IHandler*> 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) : EMPTY(const IHandler*);
+}
+
+const IHandler* XMLApplication::getHandler(const char* path) const
 {
     string wrap(path);
-    map<string,XMLPropertySet*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
+    map<string,const IHandler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
     if (i!=m_handlerMap.end())
         return i->second;
-    return m_base ? m_base->getHandlerConfig(path) : NULL;
+    return m_base ? m_base->getHandler(path) : NULL;
 }
 
 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
@@ -830,40 +845,45 @@ void XMLConfigImpl::init(bool first)
         }
 
         SAMLConfig& shibConf=SAMLConfig::getConfig();
-        ShibTargetConfig& conf=ShibTargetConfig::getConfig();
+        SPConfig& conf=SPConfig::getConfig();
         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHAR));
         if (!SHAR)
             SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Global));
+        if (!SHAR)
+            SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(OutOfProcess));
         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHIRE));
         if (!SHIRE)
             SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Local));
+        if (!SHIRE)
+            SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(InProcess));
 
         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
-        if (conf.isEnabled(ShibTargetConfig::Logging)) {
+        if (conf.isEnabled(SPConfig::Logging)) {
             const XMLCh* logger=NULL;
-            if (conf.isEnabled(ShibTargetConfig::GlobalExtensions))
+            if (conf.isEnabled(SPConfig::OutOfProcess))
                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
-            else if (conf.isEnabled(ShibTargetConfig::LocalExtensions))
+            else if (conf.isEnabled(SPConfig::InProcess))
                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
             if (!logger || !*logger)
                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
             if (logger && *logger) {
                 auto_ptr_char logpath(logger);
-                cerr << "loading new logging configuration from " << logpath.get() << "\n";
+                log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
                 try {
                     PropertyConfigurator::configure(logpath.get());
-                    cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
                 }
                 catch (ConfigureFailure& e) {
-                    cerr << "Error reading logging configuration: " << e.what() << "\n";
+                    log.error("Error reading logging configuration: %s",e.what());
                 }
             }
         }
         
         // First load any property sets.
         map<string,string> root_remap;
-        root_remap["SHAR"]="Global";
-        root_remap["SHIRE"]="Local";
+        root_remap["SHAR"]="OutOfProcess";
+        root_remap["SHIRE"]="InProcess";
+        root_remap["Global"]="OutOfProcess";
+        root_remap["Local"]="InProcess";
         load(ReloadableXMLFileImpl::m_root,log,this,&root_remap);
 
         // Much of the processing can only occur on the first instantiation.
@@ -892,7 +912,7 @@ void XMLConfigImpl::init(bool first)
                 }
             }
             
-            if (conf.isEnabled(ShibTargetConfig::GlobalExtensions)) {
+            if (conf.isEnabled(SPConfig::OutOfProcess)) {
                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
                 if (exts) {
                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
@@ -916,7 +936,7 @@ void XMLConfigImpl::init(bool first)
                 }
             }
 
-            if (conf.isEnabled(ShibTargetConfig::LocalExtensions)) {
+            if (conf.isEnabled(SPConfig::InProcess)) {
                 exts=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
                 if (exts) {
                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
@@ -940,26 +960,25 @@ void XMLConfigImpl::init(bool first)
                 }
             }
             
-            // Instantiate the Listener and SessionCache objects.
-            if (conf.isEnabled(ShibTargetConfig::Listener)) {
-                IPlugIn* plugin=NULL;
+            // Instantiate the ListenerService and SessionCache objects.
+            if (conf.isEnabled(SPConfig::Listener)) {
                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(UnixListener));
                 if (exts) {
-                    log.info("building Listener of type %s...",shibtarget::XML::UnixListenerType);
-                    plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::UnixListenerType,exts);
+                    log.info("building Listener of type %s...",UNIX_LISTENER_SERVICE);
+                    m_outer->m_listener=conf.ListenerServiceManager.newPlugin(UNIX_LISTENER_SERVICE,exts);
                 }
                 else {
                     exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TCPListener));
                     if (exts) {
-                        log.info("building Listener of type %s...",shibtarget::XML::TCPListenerType);
-                        plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::TCPListenerType,exts);
+                        log.info("building Listener of type %s...",TCP_LISTENER_SERVICE);
+                        m_outer->m_listener=conf.ListenerServiceManager.newPlugin(TCP_LISTENER_SERVICE,exts);
                     }
                     else {
                         exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Listener));
                         if (exts) {
                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
                             log.info("building Listener of type %s...",type.get());
-                            plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
+                            m_outer->m_listener=conf.ListenerServiceManager.newPlugin(type.get(),exts);
                         }
                         else {
                             log.fatal("can't build Listener object, missing conf:Listener element?");
@@ -967,41 +986,39 @@ void XMLConfigImpl::init(bool first)
                         }
                     }
                 }
-                if (plugin) {
-                    IListener* listen=dynamic_cast<IListener*>(plugin);
-                    if (listen)
-                        m_outer->m_listener=listen;
-                    else {
-                        delete plugin;
-                        log.fatal("plugin was not a Listener object");
-                        throw UnsupportedExtensionException("plugin was not a Listener object");
-                    }
-                }
             }
 
-            if (conf.isEnabled(ShibTargetConfig::Caching)) {
+            if (conf.isEnabled(SPConfig::Caching)) {
                 IPlugIn* plugin=NULL;
-                exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
+                const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
+                exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
                 if (exts) {
                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
                 }
                 else {
-                    exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
+                    exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ODBCSessionCache));
                     if (exts) {
-                        log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
-                        plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
+                        log.info("building Session Cache of type %s...",shibtarget::XML::ODBCSessionCacheType);
+                        plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::ODBCSessionCacheType,exts);
                     }
                     else {
-                        exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionCache));
+                        exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
                         if (exts) {
-                            auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
-                            log.info("building Session Cache of type %s...",type.get());
-                            plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
+                            log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
+                            plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
                         }
                         else {
-                            log.fatal("can't build Session Cache object, missing conf:SessionCache element?");
-                            throw ConfigurationException("can't build Session Cache object, missing conf:SessionCache element?");
+                            exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionCache));
+                            if (exts) {
+                                auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
+                                log.info("building Session Cache of type %s...",type.get());
+                                plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
+                            }
+                            else {
+                                log.info("session cache not specified, building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
+                                plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
+                            }
                         }
                     }
                 }
@@ -1017,29 +1034,37 @@ void XMLConfigImpl::init(bool first)
                 }
                 
                 // Replay cache.
-                exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLReplayCache));
+                container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
+                exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ODBCReplayCache));
                 if (exts) {
-                    log.info("building Replay Cache of type %s...",shibtarget::XML::MySQLReplayCacheType);
-                    m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::MySQLReplayCacheType,exts);
+                    log.info("building Replay Cache of type %s...",shibtarget::XML::ODBCReplayCacheType);
+                    m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::ODBCReplayCacheType,exts);
                 }
                 else {
-                    exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ReplayCache));
+                    exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLReplayCache));
                     if (exts) {
-                        auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
-                        log.info("building Replay Cache of type %s...",type.get());
-                        m_outer->m_replayCache=IReplayCache::getInstance(type.get(),exts);
+                        log.info("building Replay Cache of type %s...",shibtarget::XML::MySQLReplayCacheType);
+                        m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::MySQLReplayCacheType,exts);
                     }
                     else {
-                        // OpenSAML default provider.
-                        log.info("building default Replay Cache...");
-                        m_outer->m_replayCache=IReplayCache::getInstance();
+                        exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ReplayCache));
+                        if (exts) {
+                            auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
+                            log.info("building Replay Cache of type %s...",type.get());
+                            m_outer->m_replayCache=IReplayCache::getInstance(type.get(),exts);
+                        }
+                        else {
+                            // OpenSAML default provider.
+                            log.info("building default Replay Cache...");
+                            m_outer->m_replayCache=IReplayCache::getInstance();
+                        }
                     }
                 }
             }
         }
         
         // Back to the fully dynamic stuff...next up is the Request Mapper.
-        if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
+        if (conf.isEnabled(SPConfig::RequestMapper)) {
             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
             if (child) {
                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
@@ -1064,7 +1089,7 @@ void XMLConfigImpl::init(bool first)
         
         // Now we load any credentials providers.
         DOMNodeList* nlist;
-        if (conf.isEnabled(ShibTargetConfig::Credentials)) {
+        if (conf.isEnabled(SPConfig::Credentials)) {
             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialsProvider));
             for (unsigned int i=0; nlist && i<nlist->getLength(); i++) {
                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
@@ -1128,17 +1153,20 @@ void XMLConfigImpl::init(bool first)
         // Load any overrides.
         nlist=app->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Application));
         for (unsigned int j=0; nlist && j<nlist->getLength(); j++) {
-            XMLApplication* iapp=new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(j)),defapp);
-            if (m_appmap.find(iapp->getId())!=m_appmap.end()) {
-                log.fatal("found conf:Application element with duplicate Id attribute");
-                throw ConfigurationException("found conf:Application element with duplicate Id attribute");
-            }
-            m_appmap[iapp->getId()]=iapp;
+            auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(j)),defapp));
+            if (m_appmap.find(iapp->getId())!=m_appmap.end())
+                log.crit("found conf:Application element with duplicate Id attribute, ignoring it");
+            else
+                m_appmap[iapp->getId()]=iapp.release();
         }
     }
+    catch (xmltooling::XMLToolingException& e) {
+        log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
+        throw ConfigurationException(e.what());
+    }
     catch (SAMLException& e) {
         log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
-        throw;
+        throw ConfigurationException(e.what());
     }
 #ifndef _DEBUG
     catch (...) {
@@ -1151,11 +1179,8 @@ void XMLConfigImpl::init(bool first)
 XMLConfigImpl::~XMLConfigImpl()
 {
     delete m_requestMapper;
-    for (map<string,IApplication*>::iterator i=m_appmap.begin(); i!=m_appmap.end(); i++)
-        delete i->second;
-    for (vector<ICredentials*>::iterator j=m_creds.begin(); j!=m_creds.end(); j++)
-        delete (*j);
+    for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,IApplication>());
+    for_each(m_creds.begin(),m_creds.end(),xmltooling::cleanup<ICredentials>());
     ShibConfig::getConfig().clearAttributeMappings();
-    for (vector<IAttributeFactory*>::iterator k=m_attrFactories.begin(); k!=m_attrFactories.end(); k++)
-        delete (*k);
+    for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
 }