Initial checkin of ODBC storage service
[shibboleth/sp.git] / shib-target / shib-target.cpp
index daacdad..10e86b4 100644 (file)
 # include <unistd.h>
 #endif
 
-#include <ctime>
-#include <sstream>
 #include <fstream>
-#include <stdexcept>
 
 #include <saml/SAMLConfig.h>
-#include <saml/binding/URLEncoder.h>
 #include <xercesc/util/Base64.hpp>
+#include <shibsp/AccessControl.h>
+#include <shibsp/RequestMapper.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/TemplateEngine.h>
+#include <xmltooling/util/XMLHelper.h>
 
 #ifndef HAVE_STRCASECMP
 # define strcasecmp stricmp
 #endif
 
+using namespace shibsp;
 using namespace shibtarget;
 using namespace shibboleth;
 using namespace saml;
+using namespace opensaml::saml2md;
 using namespace log4cpp;
 using namespace std;
 
 using xmltooling::TemplateEngine;
 using xmltooling::XMLToolingException;
 using xmltooling::XMLToolingConfig;
+using xmltooling::XMLHelper;
 
 namespace shibtarget {
-    class CgiParse
-    {
-    public:
-        CgiParse(const ShibTarget* st);
-        ~CgiParse();
-
-        typedef multimap<string,char*>::const_iterator walker;
-        pair<walker,walker> get_values(const char* name) const;
-        
-    private:
-        char* fmakeword(char stop, unsigned int *cl, const char** ppch);
-        char* makeword(char *line, char stop);
-        void plustospace(char *str);
-
-        multimap<string,char*> kvp_map;
-    };
 
     class ExtTemplateParameters : public TemplateEngine::TemplateParameters
     {
-        const IPropertySet* m_props;
+        const PropertySet* m_props;
     public:
         ExtTemplateParameters() : m_props(NULL) {}
         ~ExtTemplateParameters() {}
 
-        void setPropertySet(const IPropertySet* props) {
+        void setPropertySet(const PropertySet* props) {
             m_props = props;
 
             // Create a timestamp.
@@ -101,32 +87,9 @@ namespace shibtarget {
         }
     };
 
-    class ShibTargetPriv
-    {
-    public:
-        ShibTargetPriv();
-        ~ShibTargetPriv();
-
-        // Helper functions
-        void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
-        void* sendError(ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex=NULL);
-        void clearHeaders(ShibTarget* st);
-    
-    private:
-        friend class ShibTarget;
-        IRequestMapper::Settings m_settings;
-        const IApplication *m_app;
-        mutable string m_handlerURL;
-        mutable map<string,string> m_cookieMap;
-        mutable CgiParse* m_cgiParser;
-
-        ISessionCacheEntry* m_cacheEntry;
-
-        ShibTargetConfig* m_Config;
+    long _sendError(SPRequest* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex=NULL);
 
-        IConfig* m_conf;
-        IRequestMapper* m_mapper;
-    };
+    static const XMLCh SessionInitiator[] =     UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
 }
 
 
@@ -134,93 +97,53 @@ namespace shibtarget {
  * Shib Target implementation
  */
 
-ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
-
-ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
-{
-    m_priv->m_app = app;
-}
-
-ShibTarget::~ShibTarget(void)
-{
-    delete m_priv;
-}
-
-void ShibTarget::init(
-    const char* protocol,
-    const char* hostname,
-    int port,
-    const char* uri,
-    const char* content_type,
-    const char* remote_addr,
-    const char* method
-    )
-{
-#ifdef _DEBUG
-    xmltooling::NDC ndc("init");
-#endif
-
-    if (m_priv->m_app)
-        throw SAMLException("Request initialization occurred twice!");
-
-    if (method) m_method = method;
-    if (protocol) m_protocol = protocol;
-    if (hostname) m_hostname = hostname;
-    if (uri) m_uri = uri;
-    if (content_type) m_content_type = content_type;
-    if (remote_addr) m_remote_addr = remote_addr;
-    m_port = port;
-    m_priv->m_Config = &ShibTargetConfig::getConfig();
-    m_priv->get_application(this, protocol, hostname, port, uri);
-}
 
 
 // These functions implement the server-agnostic shibboleth engine
 // The web server modules implement a subclass and then call into 
 // these methods once they instantiate their request object.
 
-pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
+pair<bool,long> ShibTarget::doCheckAuthN(bool handler)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("doCheckAuthN");
 #endif
 
     const char* procState = "Request Processing Error";
-    const char* targetURL = m_url.c_str();
+    string targetURL = getRequestURL();
     ExtTemplateParameters tp;
 
     try {
-        if (!m_priv->m_app)
-            throw ConfigurationException("System uninitialized, application did not supply request information.");
+        RequestMapper::Settings settings = getRequestSettings();
+        const IApplication& app = dynamic_cast<const IApplication&>(getApplication());
 
         // If not SSL, check to see if we should block or redirect it.
-        if (!strcmp("http",getProtocol())) {
-            pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
+        if (!strcmp("http",getScheme())) {
+            pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
             if (redirectToSSL.first) {
-                if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
+                if (!strcasecmp("GET",getMethod()) || !strcasecmp("HEAD",getMethod())) {
                     // Compute the new target URL
                     string redirectURL = string("https://") + getHostname();
                     if (strcmp(redirectToSSL.second,"443")) {
                         redirectURL = redirectURL + ':' + redirectToSSL.second;
                     }
                     redirectURL += getRequestURI();
-                    return make_pair(true, sendRedirect(redirectURL));
+                    return make_pair(true, sendRedirect(redirectURL.c_str()));
                 }
                 else {
-                    tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-                    return make_pair(true,m_priv->sendError(this,"ssl", tp));
+                    tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+                    return make_pair(true,_sendError(this, "ssl", tp));
                 }
             }
         }
         
-        string hURL = getHandlerURL(targetURL);
-        const char* handlerURL=hURL.c_str();
+        const char* handlerURL=getHandlerURL(targetURL.c_str());
         if (!handlerURL)
             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
 
         // If the request URL contains the handler base URL for this application, either dispatch
         // directly (mainly Apache 2.0) or just pass back control.
-        if (strstr(targetURL,handlerURL)) {
+        if (strstr(targetURL.c_str(),handlerURL)) {
             if (handler)
                 return doHandler();
             else
@@ -228,9 +151,9 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
         }
 
         // Three settings dictate how to proceed.
-        pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
-        pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
-        pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
+        pair<bool,const char*> authType = settings.first->getString("authType");
+        pair<bool,bool> requireSession = settings.first->getBool("requireSession");
+        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
 
         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
         // then we ignore this request and consider it unprotected. Apache might lie to us if
@@ -244,10 +167,10 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
             return make_pair(true,returnDecline());
 
         // Fix for secadv 20050901
-        m_priv->clearHeaders(this);
+        clearHeaders();
 
-        pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
-        const char* session_id = getCookie(shib_cookie.first);
+        pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
+        const char* session_id = getCookie(shib_cookie.first.c_str());
         if (!session_id || !*session_id) {
             // No session.  Maybe that's acceptable?
             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
@@ -255,37 +178,34 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
 
             // No cookie, but we require a session. Initiate a new session using the indicated method.
             procState = "Session Initiator Error";
-            const IHandler* initiator=NULL;
+            const Handler* initiator=NULL;
             if (requireSessionWith.first) {
-                initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
+                initiator=app.getSessionInitiatorById(requireSessionWith.second);
                 if (!initiator)
                     throw ConfigurationException(
                         "No session initiator found with id ($1), check requireSessionWith command.",
-                        params(1,requireSessionWith.second)
+                        xmltooling::params(1,requireSessionWith.second)
                         );
             }
             else {
-                initiator=m_priv->m_app->getDefaultSessionInitiator();
+                initiator=app.getDefaultSessionInitiator();
                 if (!initiator)
                     throw ConfigurationException("No default session initiator found, check configuration.");
             }
 
-            return initiator->run(this,false);
+            return initiator->run(*this,false);
         }
 
         procState = "Session Processing Error";
+        const Session* session=NULL;
         try {
-            m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
-                session_id,
-                m_priv->m_app,
-                m_remote_addr.c_str()
-                );
+            session=getSession();
             // Make a localized exception throw if the session isn't valid.
-            if (!m_priv->m_cacheEntry)
-                throw InvalidSessionException("Session no longer valid.");
+            if (!session)
+                throw RetryableProfileException("Session no longer valid.");
         }
-        catch (SAMLException& e) {
-            log(LogLevelError, string("session processing failed: ") + e.what());
+        catch (exception& e) {
+            log(SPWarn, string("session processing failed: ") + e.what());
 
             // If no session is required, bail now.
             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
@@ -296,84 +216,75 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
                 return make_pair(true, returnOK());
 
             // Try and cast down.
-            SAMLException* base = &e;
+            exception* base = &e;
             RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
             if (trycast) {
                 // Session is invalid but we can retry -- initiate a new session.
                 procState = "Session Initiator Error";
-                const IHandler* initiator=NULL;
+                const Handler* initiator=NULL;
                 if (requireSessionWith.first) {
-                    initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
+                    initiator=app.getSessionInitiatorById(requireSessionWith.second);
                     if (!initiator)
                         throw ConfigurationException(
                             "No session initiator found with id ($1), check requireSessionWith command.",
-                            params(1,requireSessionWith.second)
+                            xmltooling::params(1,requireSessionWith.second)
                             );
                 }
                 else {
-                    initiator=m_priv->m_app->getDefaultSessionInitiator();
+                    initiator=app.getDefaultSessionInitiator();
                     if (!initiator)
                         throw ConfigurationException("No default session initiator found, check configuration.");
                 }
-                return initiator->run(this,false);
+                return initiator->run(*this,false);
             }
             throw;    // send it to the outer handler
         }
 
         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
         // Let the caller decide how to proceed.
-        log(LogLevelDebug, "doCheckAuthN succeeded");
-        return make_pair(false,(void*)NULL);
-    }
-    catch (SAMLException& e) {                  // TODO: we're going to yank this handler...
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp));
+        log(SPDebug, "doCheckAuthN succeeded");
+        return make_pair(false,0);
     }
     catch (XMLToolingException& e) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp, &e));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "session", tp, &e));
     }
 #ifndef _DEBUG
     catch (...) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = "Caught an unknown exception.";
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "session", tp));
     }
 #endif
 }
 
-pair<bool,void*> ShibTarget::doHandler(void)
+pair<bool,long> ShibTarget::doHandler(void)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("doHandler");
 #endif
 
+    const IApplication* app=NULL;
     ExtTemplateParameters tp;
     const char* procState = "Shibboleth Handler Error";
-    const char* targetURL = m_url.c_str();
+    string targetURL = getRequestURL();
 
     try {
-        if (!m_priv->m_app)
-            throw ConfigurationException("System uninitialized, application did not supply request information.");
+        RequestMapper::Settings settings = getRequestSettings();
+        app = dynamic_cast<const IApplication*>(&getApplication());
 
-        string hURL = getHandlerURL(targetURL);
-        const char* handlerURL=hURL.c_str();
+        const char* handlerURL=getHandlerURL(targetURL.c_str());
         if (!handlerURL)
             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
 
         // Make sure we only process handler requests.
-        if (!strstr(targetURL,handlerURL))
+        if (!strstr(targetURL.c_str(),handlerURL))
             return make_pair(true, returnDecline());
 
-        const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
+        const PropertySet* sessionProps=app->getPropertySet("Sessions");
         if (!sessionProps)
             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
 
@@ -381,91 +292,80 @@ pair<bool,void*> ShibTarget::doHandler(void)
         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
       
         // Make sure this is SSL, if it should be
-        if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
+        if ((!handlerSSL.first || handlerSSL.second) && strcmp(getScheme(),"https"))
             throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
 
         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
         // so the path info is the next character (or null).
-        const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
+        const Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
         if (!handler)
-            throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
+            throw opensaml::BindingException("Shibboleth handler invoked at an unconfigured location.");
 
-        if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService)))
+        if (XMLHelper::isNodeNamed(handler->getElement(),samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME))
             procState = "Session Creation Error";
-        else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
+        else if (XMLString::equals(handler->getElement()->getLocalName(),SessionInitiator))
             procState = "Session Initiator Error";
-        else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService)))
+        else if (XMLHelper::isNodeNamed(handler->getElement(),samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME))
             procState = "Session Termination Error";
-        else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService)))
-            procState = "Diagnostics Error";
         else
-            procState = "Extension Service Error";
-        pair<bool,void*> hret=handler->run(this);
+            procState = "Protocol Handler Error";
+        pair<bool,long> hret=handler->run(*this);
 
         // Did the handler run successfully?
         if (hret.first)
             return hret;
        
-        throw XMLToolingException("Configured Shibboleth handler failed to process the request.");
+        throw opensaml::BindingException("Configured Shibboleth handler failed to process the request.");
     }
     catch (MetadataException& e) {
         tp.m_map["errorText"] = e.what();
         // See if a metadata error page is installed.
-        const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
+        const PropertySet* props=app->getPropertySet("Errors");
         if (props) {
             pair<bool,const char*> p=props->getString("metadata");
             if (p.first) {
                 tp.m_map["errorType"] = procState;
-                if (targetURL)
-                    tp.m_map["requestURL"] = targetURL;
-                return make_pair(true,m_priv->sendError(this, "metadata", tp));
+                tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+                return make_pair(true,_sendError(this, "metadata", tp));
             }
         }
         throw;
     }
-    catch (SAMLException& e) {
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp));
-    }
     catch (XMLToolingException& e) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp, &e));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "session", tp, &e));
     }
 #ifndef _DEBUG
     catch (...) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = "Caught an unknown exception.";
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "session", tp));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "session", tp));
     }
 #endif
 }
 
-pair<bool,void*> ShibTarget::doCheckAuthZ(void)
+pair<bool,long> ShibTarget::doCheckAuthZ(void)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("doCheckAuthZ");
 #endif
 
+    const IApplication* app=NULL;
     ExtTemplateParameters tp;
     const char* procState = "Authorization Processing Error";
-    const char* targetURL = m_url.c_str();
+    string targetURL = getRequestURL();
 
     try {
-        if (!m_priv->m_app)
-            throw ConfigurationException("System uninitialized, application did not supply request information.");
+        RequestMapper::Settings settings = getRequestSettings();
+        app = dynamic_cast<const IApplication*>(&getApplication());
 
         // Three settings dictate how to proceed.
-        pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
-        pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
-        pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
+        pair<bool,const char*> authType = settings.first->getString("authType");
+        pair<bool,bool> requireSession = settings.first->getBool("requireSession");
+        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
 
         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
         // then we ignore this request and consider it unprotected. Apache might lie to us if
@@ -479,118 +379,98 @@ pair<bool,void*> ShibTarget::doCheckAuthZ(void)
             return make_pair(true,returnDecline());
 
         // Do we have an access control plugin?
-        if (m_priv->m_settings.second) {
-               
-               if (!m_priv->m_cacheEntry) {
-                   // No data yet, so we may need to try and get the session.
-                       pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
-                       const char *session_id = getCookie(shib_cookie.first);
-                   try {
-                               if (session_id && *session_id) {
-                        m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
-                            session_id,
-                            m_priv->m_app,
-                            m_remote_addr.c_str()
-                            );
-                               }
-                   }
-                   catch (SAMLException&) {
-                       log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
-                   }
-               }
+        if (settings.second) {
+            const Session* session =NULL;
+               pair<string,const char*> shib_cookie=app->getCookieNameProps("_shibsession_");
+            const char *session_id = getCookie(shib_cookie.first.c_str());
+            try {
+                       if (session_id && *session_id) {
+                    session = getSession();
+                       }
+            }
+            catch (exception&) {
+               log(SPWarn, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
+            }
        
-            Locker acllock(m_priv->m_settings.second);
-            if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
+            xmltooling::Locker acllock(settings.second);
+            if (settings.second->authorized(*this,session)) {
                 // Let the caller decide how to proceed.
-                log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
-                return make_pair(false,(void*)NULL);
+                log(SPDebug, "doCheckAuthZ: access control provider granted access");
+                return make_pair(false,0);
             }
             else {
-                log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
-                if (targetURL)
-                    tp.m_map["requestURL"] = targetURL;
-                return make_pair(true,m_priv->sendError(this, "access", tp));
+                log(SPWarn, "doCheckAuthZ: access control provider denied access");
+                tp.m_map["requestURL"] = targetURL;
+                return make_pair(true,_sendError(this, "access", tp));
             }
+            return make_pair(false,0);
         }
         else
             return make_pair(true,returnDecline());
     }
-    catch (SAMLException& e) {
+    catch (exception& e) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "access", tp));
-    }
-    catch (XMLToolingException& e) {
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "access", tp, &e));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "access", tp));
     }
 #ifndef _DEBUG
     catch (...) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = "Caught an unknown exception.";
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "access", tp));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "access", tp));
     }
 #endif
 }
 
-pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
+pair<bool,long> ShibTarget::doExportAssertions(bool requireSession)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("doExportAssertions");
 #endif
 
+    const IApplication* app=NULL;
     ExtTemplateParameters tp;
     const char* procState = "Attribute Processing Error";
-    const char* targetURL = m_url.c_str();
+    string targetURL = getRequestURL();
 
     try {
-        if (!m_priv->m_app)
-            throw ConfigurationException("System uninitialized, application did not supply request information.");
-
-        if (!m_priv->m_cacheEntry) {
-            // No data yet, so we need to get the session. This can only happen
-            // if the call to doCheckAuthn doesn't happen in the same object lifetime.
-               pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
-               const char *session_id = getCookie(shib_cookie.first);
-            try {
-                       if (session_id && *session_id) {
-                    m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
-                        session_id,
-                        m_priv->m_app,
-                        m_remote_addr.c_str()
-                        );
-                       }
-            }
-            catch (SAMLException&) {
-               log(LogLevelError, "unable to obtain session information to export into request headers");
-               // If we have to have a session, then this is a fatal error.
-               if (requireSession)
-                       throw;
-            }
+        RequestMapper::Settings settings = getRequestSettings();
+        app = dynamic_cast<const IApplication*>(&getApplication());
+
+        const Session* session=NULL;
+        pair<string,const char*> shib_cookie=app->getCookieNameProps("_shibsession_");
+        const char *session_id = getCookie(shib_cookie.first.c_str());
+        try {
+               if (session_id && *session_id) {
+                session = getSession();
+               }
+        }
+        catch (exception&) {
+               log(SPWarn, "unable to obtain session information to export into request headers");
+               // If we have to have a session, then this is a fatal error.
+               if (requireSession)
+                       throw;
         }
 
                // Still no data?
-        if (!m_priv->m_cacheEntry) {
+        if (!session) {
                if (requireSession)
-                       throw InvalidSessionException("Unable to obtain session information for request.");
+                       throw RetryableProfileException("Unable to obtain session information for request.");
                else
-                       return make_pair(false,(void*)NULL);    // just bail silently
+                       return make_pair(false,0);      // just bail silently
         }
         
+        /*
+        TODO: port to new cache API
         // Extract data from session.
-        pair<const char*,const SAMLSubject*> sub=m_priv->m_cacheEntry->getSubject(false,true);
-        pair<const char*,const SAMLResponse*> unfiltered=m_priv->m_cacheEntry->getTokens(true,false);
-        pair<const char*,const SAMLResponse*> filtered=m_priv->m_cacheEntry->getTokens(false,true);
+        pair<const char*,const SAMLSubject*> sub=m_cacheEntry->getSubject(false,true);
+        pair<const char*,const SAMLResponse*> unfiltered=m_cacheEntry->getTokens(true,false);
+        pair<const char*,const SAMLResponse*> filtered=m_cacheEntry->getTokens(false,true);
 
         // Maybe export the tokens.
-        pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
+        pair<bool,bool> exp=m_settings.first->getBool("exportAssertion");
         if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
             unsigned int outlen;
             XMLByte* serialized =
@@ -605,17 +485,17 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
         }
 
         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
-        setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
-        setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
-        setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
+        setHeader("Shib-Origin-Site", m_cacheEntry->getProviderId());
+        setHeader("Shib-Identity-Provider", m_cacheEntry->getProviderId());
+        setHeader("Shib-Authentication-Method", m_cacheEntry->getAuthnContext());
         
         // Get the AAP providers, which contain the attribute policy info.
-        Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
+        Iterator<IAAP*> provs=m_app->getAAPProviders();
 
         // Export NameID?
         while (provs.hasNext()) {
             IAAP* aap=provs.next();
-            Locker locker(aap);
+            xmltooling::Locker locker(aap);
             const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
             const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
             if (rule && rule->getHeader()) {
@@ -629,7 +509,7 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
             }
         }
         
-        setHeader("Shib-Application-ID", m_priv->m_app->getId());
+        setHeader("Shib-Application-ID", m_app->getId());
     
         // Export the attributes.
         Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));
@@ -648,17 +528,17 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
                     provs.reset();
                     while (provs.hasNext()) {
                         IAAP* aap=provs.next();
-                        Locker locker(aap);
+                        xmltooling::Locker locker(aap);
                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
                         if (!rule || !rule->getHeader())
                             continue;
                     
                         Iterator<string> vals=attr->getSingleByteValues();
                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
-                            setRemoteUser(vals.next());
+                            setRemoteUser(vals.next().c_str());
                         else {
                             int it=0;
-                            string header = getHeader(rule->getHeader());
+                            string header = getSecureHeader(rule->getHeader());
                             if (!header.empty())
                                 it++;
                             for (; vals.hasNext(); it++) {
@@ -673,436 +553,89 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
                                     header += ";";
                                 header += value;
                             }
-                            setHeader(rule->getHeader(), header);
+                            setHeader(rule->getHeader(), header.c_str());
                         }
                     }
                 }
             }
         }
+        */
     
-        return make_pair(false,(void*)NULL);
-    }
-    catch (SAMLException& e) {
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "rm", tp));
+        return make_pair(false,0);
     }
     catch (XMLToolingException& e) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = e.what();
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "rm", tp, &e));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "rm", tp, &e));
     }
 #ifndef _DEBUG
     catch (...) {
         tp.m_map["errorType"] = procState;
         tp.m_map["errorText"] = "Caught an unknown exception.";
-        if (targetURL)
-            tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
-        return make_pair(true,m_priv->sendError(this, "rm", tp));
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,_sendError(this, "rm", tp));
     }
 #endif
 }
 
-const char* ShibTarget::getRequestParameter(const char* param, size_t index) const
-{
-    if (!m_priv->m_cgiParser)
-        m_priv->m_cgiParser=new CgiParse(this);
-    
-    pair<CgiParse::walker,CgiParse::walker> bounds=m_priv->m_cgiParser->get_values(param);
-    
-    // Advance to the right index.
-    while (index && bounds.first!=bounds.second) {
-        index--;
-        bounds.first++;
-    }
-
-    return (bounds.first==bounds.second) ? NULL : bounds.first->second;
-}
-
-const char* ShibTarget::getCookie(const string& name) const
-{
-    if (m_priv->m_cookieMap.empty()) {
-        string cookies=getCookies();
-
-        string::size_type pos=0,cname,namelen,val,vallen;
-        while (pos !=string::npos && pos < cookies.length()) {
-            while (isspace(cookies[pos])) pos++;
-            cname=pos;
-            pos=cookies.find_first_of("=",pos);
-            if (pos == string::npos)
-                break;
-            namelen=pos-cname;
-            pos++;
-            if (pos==cookies.length())
-                break;
-            val=pos;
-            pos=cookies.find_first_of(";",pos);
-            if (pos != string::npos) {
-                vallen=pos-val;
-                pos++;
-                m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
-            }
-            else
-                m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
-        }
-    }
-    map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
-    return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
-}
-
-pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
-{
-    static const char* defProps="; path=/";
-    
-    const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
-    if (props) {
-        pair<bool,const char*> p=props->getString("cookieProps");
-        if (!p.first)
-            p.second=defProps;
-        pair<bool,const char*> p2=props->getString("cookieName");
-        if (p2.first)
-            return make_pair(string(prefix) + p2.second,p.second);
-        return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
-    }
-    
-    // Shouldn't happen, but just in case..
-    return pair<string,const char*>(prefix,defProps);
-}
-
-string ShibTarget::getHandlerURL(const char* resource) const
-{
-    if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
-        return m_priv->m_handlerURL;
-        
-    if (!m_priv->m_app)
-        throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
-
-    bool ssl_only=false;
-    const char* handler=NULL;
-    const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
-    if (props) {
-        pair<bool,bool> p=props->getBool("handlerSSL");
-        if (p.first)
-            ssl_only=p.second;
-        pair<bool,const char*> p2=props->getString("handlerURL");
-        if (p2.first)
-            handler=p2.second;
-    }
-    
-    // Should never happen...
-    if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
-        throw ConfigurationException(
-            "Invalid handlerURL property ($1) in Application ($2)",
-            params(2, handler ? handler : "null", m_priv->m_app->getId())
-            );
-
-    // The "handlerURL" property can be in one of three formats:
-    //
-    // 1) a full URI:       http://host/foo/bar
-    // 2) a hostless URI:   http:///foo/bar
-    // 3) a relative path:  /foo/bar
-    //
-    // #  Protocol  Host        Path
-    // 1  handler   handler     handler
-    // 2  handler   resource    handler
-    // 3  resource  resource    handler
-    //
-    // note: if ssl_only is true, make sure the protocol is https
-
-    const char* path = NULL;
-
-    // Decide whether to use the handler or the resource for the "protocol"
-    const char* prot;
-    if (*handler != '/') {
-        prot = handler;
-    }
-    else {
-        prot = resource;
-        path = handler;
-    }
-
-    // break apart the "protocol" string into protocol, host, and "the rest"
-    const char* colon=strchr(prot,':');
-    colon += 3;
-    const char* slash=strchr(colon,'/');
-    if (!path)
-        path = slash;
-
-    // Compute the actual protocol and store in member.
-    if (ssl_only)
-        m_priv->m_handlerURL.assign("https://");
-    else
-        m_priv->m_handlerURL.assign(prot, colon-prot);
-
-    // create the "host" from either the colon/slash or from the target string
-    // If prot == handler then we're in either #1 or #2, else #3.
-    // If slash == colon then we're in #2.
-    if (prot != handler || slash == colon) {
-        colon = strchr(resource, ':');
-        colon += 3;      // Get past the ://
-        slash = strchr(colon, '/');
-    }
-    string host(colon, (slash ? slash-colon : strlen(colon)));
-
-    // Build the handler URL
-    m_priv->m_handlerURL+=host + path;
-    return m_priv->m_handlerURL;
-}
-
-void ShibTarget::log(ShibLogLevel level, const string& msg)
-{
-    Category::getInstance("shibtarget.ShibTarget").log(
-        (level == LogLevelDebug ? Priority::DEBUG :
-        (level == LogLevelInfo ? Priority::INFO :
-        (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
-        msg
-    );
-}
-
-const IApplication* ShibTarget::getApplication() const
-{
-    return m_priv->m_app;
-}
-
-const IConfig* ShibTarget::getConfig() const
-{
-    return m_priv->m_conf;
-}
-
-void* ShibTarget::returnDecline(void)
-{
-    return NULL;
-}
-
-void* ShibTarget::returnOK(void)
-{
-    return NULL;
-}
-
 /*************************************************************************
  * Shib Target Private implementation
  */
 
-ShibTargetPriv::ShibTargetPriv()
-    : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL), m_cgiParser(NULL) {}
-
-ShibTargetPriv::~ShibTargetPriv()
-{
-    if (m_cacheEntry) {
-        m_cacheEntry->unlock();
-        m_cacheEntry = NULL;
-    }
-
-    if (m_mapper) {
-        m_mapper->unlock();
-        m_mapper = NULL;
-    }
-    
-    if (m_conf) {
-        m_conf->unlock();
-        m_conf = NULL;
-    }
-
-    delete m_cgiParser;
-    m_app = NULL;
-    m_Config = NULL;
-}
-
-void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
-{
-  if (m_app)
-    return;
-
-  // XXX: Do we need to keep conf and mapper locked while we hold m_app?
-  // TODO: No, should be able to hold the conf but release the mapper.
-
-  // We lock the configuration system for the duration.
-  m_conf=m_Config->getINI();
-  m_conf->lock();
-    
-  // Map request to application and content settings.
-  m_mapper=m_conf->getRequestMapper();
-  m_mapper->lock();
-
-  // Obtain the application settings from the parsed URL
-  m_settings = m_mapper->getSettings(st);
-
-  // Now find the application from the URL settings
-  pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
-  m_app=m_conf->getApplication(application_id.second);
-  if (!m_app) {
-    m_mapper->unlock();
-    m_mapper = NULL;
-    m_conf->unlock();
-    m_conf = NULL;
-    throw ConfigurationException("Unable to map request to application settings, check configuration.");
-  }
-
-  // Compute the full target URL
-  st->m_url = protocol + "://" + hostname;
-  if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
-       ostringstream portstr;
-       portstr << port;
-    st->m_url += ":" + portstr.str();
-  }
-  st->m_url += uri;
-}
-
-void* ShibTargetPriv::sendError(
-    ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex
+long shibtarget::_sendError(
+    SPRequest* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex
     )
 {
-    ShibTarget::header_t hdrs[] = {
-        ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
-        ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
-        };
-    
+    st->setContentType("text/html");
+    st->setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
+    st->setResponseHeader("Cache-Control","private,no-store,no-cache");
+
     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
-    const IPropertySet* props=m_app->getPropertySet("Errors");
+    const PropertySet* props=st->getApplication().getPropertySet("Errors");
     if (props) {
         pair<bool,const char*> p=props->getString(page);
         if (p.first) {
             ifstream infile(p.second);
             if (infile) {
                 tp.setPropertySet(props);
-                ostringstream ostr;
-                engine->run(infile, ostr, tp, ex);
-                return st->sendPage(ostr.str().c_str(), 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
+                stringstream str;
+                engine->run(infile, str, tp, ex);
+                return st->sendResponse(str);
             }
         }
-        else if (!strcmp(page,"access"))
-            return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
+        else if (!strcmp(page,"access")) {
+            istringstream msg("Access Denied");
+            return static_cast<opensaml::GenericResponse*>(st)->sendResponse(msg, opensaml::HTTPResponse::SAML_HTTP_STATUS_FORBIDDEN);
+        }
     }
 
-    string errstr = string("sendError could not process error template (") + page + ") for application (";
-    errstr += m_app->getId();
-    errstr += ")";
-    st->log(ShibTarget::LogLevelError, errstr);
-    return st->sendPage(
-        "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
-        );
+    string errstr = string("sendError could not process error template (") + page + ")";
+    st->log(SPRequest::SPError, errstr);
+    istringstream msg("Internal Server Error. Please contact the site administrator.");
+    return st->sendError(msg);
 }
 
-void ShibTargetPriv::clearHeaders(ShibTarget* st)
+void ShibTarget::clearHeaders()
 {
     // Clear invariant stuff.
-    st->clearHeader("Shib-Origin-Site");
-    st->clearHeader("Shib-Identity-Provider");
-    st->clearHeader("Shib-Authentication-Method");
-    st->clearHeader("Shib-NameIdentifier-Format");
-    st->clearHeader("Shib-Attributes");
-    st->clearHeader("Shib-Application-ID");
+    clearHeader("Shib-Origin-Site");
+    clearHeader("Shib-Identity-Provider");
+    clearHeader("Shib-Authentication-Method");
+    clearHeader("Shib-NameIdentifier-Format");
+    clearHeader("Shib-Attributes");
+    clearHeader("Shib-Application-ID");
 
     // Clear out the list of mapped attributes
-    Iterator<IAAP*> provs=m_app->getAAPProviders();
+    Iterator<IAAP*> provs=dynamic_cast<const IApplication&>(getApplication()).getAAPProviders();
     while (provs.hasNext()) {
         IAAP* aap=provs.next();
-        Locker locker(aap);
+        xmltooling::Locker locker(aap);
         Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
         while (rules.hasNext()) {
             const char* header=rules.next()->getHeader();
             if (header)
-                st->clearHeader(header);
+                clearHeader(header);
         }
     }
 }
-
-/*************************************************************************
- * CGI Parser implementation
- */
-
-CgiParse::CgiParse(const ShibTarget* st)
-{
-    const char* pch=NULL;
-    if (!strcmp(st->getRequestMethod(),"POST"))
-        pch=st->getRequestBody();
-    else
-        pch=st->getQueryString();
-    size_t cl=pch ? strlen(pch) : 0;
-    
-        
-    while (cl && pch) {
-        char *name;
-        char *value;
-        value=fmakeword('&',&cl,&pch);
-        plustospace(value);
-        opensaml::SAMLConfig::getConfig().getURLEncoder()->decode(value);
-        name=makeword(value,'=');
-        kvp_map.insert(pair<string,char*>(name,value));
-        free(name);
-    }
-}
-
-CgiParse::~CgiParse()
-{
-    for (multimap<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
-        free(i->second);
-}
-
-pair<CgiParse::walker,CgiParse::walker> CgiParse::get_values(const char* name) const
-{
-    return kvp_map.equal_range(name);
-}
-
-/* Parsing routines modified from NCSA source. */
-char* CgiParse::makeword(char *line, char stop)
-{
-    int x = 0,y;
-    char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
-
-    for(x=0;((line[x]) && (line[x] != stop));x++)
-        word[x] = line[x];
-
-    word[x] = '\0';
-    if(line[x])
-        ++x;
-    y=0;
-
-    while(line[x])
-      line[y++] = line[x++];
-    line[y] = '\0';
-    return word;
-}
-
-char* CgiParse::fmakeword(char stop, size_t *cl, const char** ppch)
-{
-    int wsize;
-    char *word;
-    int ll;
-
-    wsize = 1024;
-    ll=0;
-    word = (char *) malloc(sizeof(char) * (wsize + 1));
-
-    while(1)
-    {
-        word[ll] = *((*ppch)++);
-        if(ll==wsize-1)
-        {
-            word[ll+1] = '\0';
-            wsize+=1024;
-            word = (char *)realloc(word,sizeof(char)*(wsize+1));
-        }
-        --(*cl);
-        if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
-        {
-            if(word[ll] != stop)
-                ll++;
-            word[ll] = '\0';
-            return word;
-        }
-        ++ll;
-    }
-}
-
-void CgiParse::plustospace(char *str)
-{
-    register int x;
-
-    for(x=0;str[x];x++)
-        if(str[x] == '+') str[x] = ' ';
-}