Next integration phase, metadata and trust conversion.
[shibboleth/sp.git] / shib-target / shib-target.cpp
index b2e4cc4..acf5fce 100644 (file)
@@ -1,50 +1,17 @@
 /*
- * The Shibboleth License, Version 1.
- * Copyright (c) 2002
- * University Corporation for Advanced Internet Development, Inc.
- * All rights reserved
+ *  Copyright 2001-2005 Internet2
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution, if any, must include
- * the following acknowledgment: "This product includes software developed by
- * the University Corporation for Advanced Internet Development
- * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
- * may appear in the software itself, if and wherever such third-party
- * acknowledgments normally appear.
- *
- * Neither the name of Shibboleth nor the names of its contributors, nor
- * Internet2, nor the University Corporation for Advanced Internet Development,
- * Inc., nor UCAID may be used to endorse or promote products derived from this
- * software without specific prior written permission. For written permission,
- * please contact shibboleth@shibboleth.org
- *
- * Products derived from this software may not be called Shibboleth, Internet2,
- * UCAID, or the University Corporation for Advanced Internet Development, nor
- * may Shibboleth appear in their name, without prior written permission of the
- * University Corporation for Advanced Internet Development.
- *
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
- * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
- * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
- * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 /*
 # include <unistd.h>
 #endif
 
+#include <ctime>
 #include <sstream>
 #include <fstream>
 #include <stdexcept>
 
-#include <shib/shib-threads.h>
+#include <saml/SAMLConfig.h>
+#include <saml/binding/URLEncoder.h>
 #include <xercesc/util/Base64.hpp>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/TemplateEngine.h>
+#include <xmltooling/util/XMLHelper.h>
 
 #ifndef HAVE_STRCASECMP
 # define strcasecmp stricmp
 #endif
 
-using namespace std;
-using namespace saml;
-using namespace shibboleth;
+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 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, ShibMLP &mlp);
+    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 PropertySet* m_props;
+    public:
+        ExtTemplateParameters() : m_props(NULL) {}
+        ~ExtTemplateParameters() {}
+
+        void setPropertySet(const PropertySet* props) {
+            m_props = props;
+
+            // Create a timestamp.
+            time_t now = time(NULL);
+#ifdef HAVE_CTIME_R
+            char timebuf[32];
+            m_map["now"] = ctime_r(&now,timebuf);
+#else
+            m_map["now"] = ctime(&now);
+#endif
+        }
+
+        const char* getParameter(const char* name) const {
+            const char* pch = TemplateParameters::getParameter(name);
+            if (pch || !m_props)
+                return pch;
+            pair<bool,const char*> p = m_props->getString(name);
+            return p.first ? p.second : NULL;
+        }
+    };
+
+    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);
     
-    // Handlers do the real Shibboleth work
-    pair<bool,void*> dispatch(
-        ShibTarget* st,
-        const IPropertySet* handler,
-        bool isHandler=true,
-        const char* forceType=NULL
-        ) const;
-
-  private:
-    friend class ShibTarget;
-    IRequestMapper::Settings m_settings;
-    const IApplication *m_app;
-    mutable string m_handlerURL;
-    mutable map<string,string> m_cookieMap;
-
-    ISessionCacheEntry* m_cacheEntry;
-
-    ShibTargetConfig* m_Config;
-
-    IConfig* m_conf;
-    IRequestMapper* m_mapper;
-  };
+    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;
+
+        IConfig* m_conf;
+        IRequestMapper* m_mapper;
+    };
 }
 
 
@@ -119,20 +138,16 @@ namespace shibtarget {
  * Shib Target implementation
  */
 
-ShibTarget::ShibTarget(void) : m_priv(NULL)
-{
-  m_priv = new ShibTargetPriv();
-}
+ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
 
-ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
+ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
 {
-  m_priv = new ShibTargetPriv();
-  m_priv->m_app = app;
+    m_priv->m_app = app;
 }
 
 ShibTarget::~ShibTarget(void)
 {
-  if (m_priv) delete m_priv;
+    delete m_priv;
 }
 
 void ShibTarget::init(
@@ -146,21 +161,21 @@ void ShibTarget::init(
     )
 {
 #ifdef _DEBUG
-  saml::NDC ndc("init");
+    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);
+    if (m_priv->m_app)
+        throw XMLToolingException("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);
 }
 
 
@@ -171,17 +186,37 @@ void ShibTarget::init(
 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
 {
 #ifdef _DEBUG
-    saml::NDC ndc("doCheckAuthN");
+    xmltooling::NDC ndc("doCheckAuthN");
 #endif
 
     const char* procState = "Request Processing Error";
     const char* targetURL = m_url.c_str();
-    ShibMLP mlp;
+    ExtTemplateParameters tp;
 
     try {
         if (!m_priv->m_app)
             throw ConfigurationException("System uninitialized, application did not supply request information.");
 
+        // 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 (redirectToSSL.first) {
+                if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
+                    // 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));
+                }
+                else {
+                    tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
+                    return make_pair(true,m_priv->sendError(this,"ssl", tp));
+                }
+            }
+        }
+        
         string hURL = getHandlerURL(targetURL);
         const char* handlerURL=hURL.c_str();
         if (!handlerURL)
@@ -193,7 +228,7 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
             if (handler)
                 return doHandler();
             else
-                return pair<bool,void*>(true, returnOK());
+                return make_pair(true, returnOK());
         }
 
         // Three settings dictate how to proceed.
@@ -208,46 +243,52 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
 #ifdef HAVE_STRCASECMP
                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
 #else
-                (!authType.first || stricmp(authType.second,"shibboleth")))
+                (!authType.first || _stricmp(authType.second,"shibboleth")))
 #endif
-            return pair<bool,void*>(true,returnDecline());
+            return make_pair(true,returnDecline());
+
+        // Fix for secadv 20050901
+        m_priv->clearHeaders(this);
 
         pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
         const char* session_id = getCookie(shib_cookie.first);
         if (!session_id || !*session_id) {
             // No session.  Maybe that's acceptable?
             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
-                return pair<bool,void*>(true,returnOK());
+                return make_pair(true,returnOK());
 
             // No cookie, but we require a session. Initiate a new session using the indicated method.
             procState = "Session Initiator Error";
-            const IPropertySet* initiator=NULL;
-            if (requireSessionWith.first)
+            const IHandler* initiator=NULL;
+            if (requireSessionWith.first) {
                 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
-            if (!initiator)
-                initiator=m_priv->m_app->getDefaultSessionInitiator();
-            
-            // Standard handler element, so we dispatch normally.
-            if (initiator)
-                return m_priv->dispatch(this,initiator,false);
+                if (!initiator)
+                    throw ConfigurationException(
+                        "No session initiator found with id ($1), check requireSessionWith command.",
+                        xmltooling::params(1,requireSessionWith.second)
+                        );
+            }
             else {
-                // Legacy config support maps the Sessions element to the Shib profile.
-                auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
-                return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
+                initiator=m_priv->m_app->getDefaultSessionInitiator();
+                if (!initiator)
+                    throw ConfigurationException("No default session initiator found, check configuration.");
             }
+
+            return initiator->run(this,false);
         }
 
         procState = "Session Processing Error";
         try {
-            // Localized exception throw if the session isn't valid.
-            m_priv->m_conf->getListener()->sessionGet(
-                m_priv->m_app,
+            m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
                 session_id,
-                m_remote_addr.c_str(),
-                &m_priv->m_cacheEntry
+                m_priv->m_app,
+                m_remote_addr.c_str()
                 );
+            // Make a localized exception throw if the session isn't valid.
+            if (!m_priv->m_cacheEntry)
+                throw RetryableProfileException("Session no longer valid.");
         }
-        catch (SAMLException& e) {
+        catch (exception& e) {
             log(LogLevelError, string("session processing failed: ") + e.what());
 
             // If no session is required, bail now.
@@ -256,27 +297,29 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
                 // to fail when it can't locate anything to process the
                 // AuthType.  No session plus requireSession false means
                 // do not authenticate the user at this time.
-                return pair<bool,void*>(true, returnOK());
+                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 IPropertySet* initiator=NULL;
-                if (requireSessionWith.first)
+                const IHandler* initiator=NULL;
+                if (requireSessionWith.first) {
                     initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
-                if (!initiator)
-                    initiator=m_priv->m_app->getDefaultSessionInitiator();
-                // Standard handler element, so we dispatch normally.
-                if (initiator)
-                    return m_priv->dispatch(this,initiator,false);
+                    if (!initiator)
+                        throw ConfigurationException(
+                            "No session initiator found with id ($1), check requireSessionWith command.",
+                            xmltooling::params(1,requireSessionWith.second)
+                            );
+                }
                 else {
-                    // Legacy config support maps the Sessions element to the Shib profile.
-                    auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
-                    return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
+                    initiator=m_priv->m_app->getDefaultSessionInitiator();
+                    if (!initiator)
+                        throw ConfigurationException("No default session initiator found, check configuration.");
                 }
+                return initiator->run(this,false);
             }
             throw;    // send it to the outer handler
         }
@@ -284,34 +327,35 @@ pair<bool,void*> ShibTarget::doCheckAuthN(bool 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 pair<bool,void*>(false,NULL);
+        return make_pair(false,(void*)NULL);
     }
-    catch (SAMLException& e) {
-        mlp.insert(e);
+    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));
     }
 #ifndef _DEBUG
     catch (...) {
-        mlp.insert("errorText", "Caught an unknown exception.");
+        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));
     }
 #endif
-
-    // If we get here then we've got an error.
-    mlp.insert("errorType", procState);
-    if (targetURL)
-        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
-
-    return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
 }
 
 pair<bool,void*> ShibTarget::doHandler(void)
 {
 #ifdef _DEBUG
-    saml::NDC ndc("doHandler");
+    xmltooling::NDC ndc("doHandler");
 #endif
 
+    ExtTemplateParameters tp;
     const char* procState = "Shibboleth Handler Error";
     const char* targetURL = m_url.c_str();
-    ShibMLP mlp;
 
     try {
         if (!m_priv->m_app)
@@ -324,9 +368,9 @@ pair<bool,void*> ShibTarget::doHandler(void)
 
         // Make sure we only process handler requests.
         if (!strstr(targetURL,handlerURL))
-            return pair<bool,void*>(true, returnDecline());
+            return make_pair(true, returnDecline());
 
-        const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
+        const PropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
         if (!sessionProps)
             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
 
@@ -335,89 +379,72 @@ pair<bool,void*> ShibTarget::doHandler(void)
       
         // Make sure this is SSL, if it should be
         if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
-            throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
+            throw opensaml::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 IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
-        if (handler) {
-            if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
-                procState = "Session Creation Error";
-                return m_priv->dispatch(this,handler);
-            }
-            else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
-                procState = "Session Initiator Error";
-                return m_priv->dispatch(this,handler);
-            }
-            else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
-                procState = "Session Termination Error";
-                return m_priv->dispatch(this,handler);
-            }
-            else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
-                procState = "Diagnostics Error";
-                return m_priv->dispatch(this,handler);
-            }
-            else {
-                procState = "Extension Service Error";
-                return m_priv->dispatch(this,handler);
-            }
-        }
-        
-        if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
-            throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
-        
-        // This is a legacy direct execution of the handler (the old shireURL).
-        // If this is a GET, we see if it's a lazy session request, otherwise
-        // assume it's a SAML 1.x POST profile response and process it.
-        if (!strcasecmp(m_method.c_str(), "GET")) {
+        const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
+        if (!handler)
+            throw opensaml::BindingException("Shibboleth handler invoked at an unconfigured location.");
+
+        if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,SHIBT_L(AssertionConsumerService)))
+            procState = "Session Creation Error";
+        else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
             procState = "Session Initiator Error";
-            auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
-            return m_priv->dispatch(this, sessionProps, true, binding.get());
-        }
-        
-        procState = "Session Creation Error";
-        auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
-        return m_priv->dispatch(this, sessionProps, true, binding.get());
+        else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,SHIBT_L(SingleLogoutService)))
+            procState = "Session Termination Error";
+        else if (XMLHelper::isNodeNamed(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);
+
+        // Did the handler run successfully?
+        if (hret.first)
+            return hret;
+       
+        throw opensaml::BindingException("Configured Shibboleth handler failed to process the request.");
     }
     catch (MetadataException& e) {
-        mlp.insert(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=m_priv->m_app->getPropertySet("Errors");
         if (props) {
             pair<bool,const char*> p=props->getString("metadata");
             if (p.first) {
-                mlp.insert("errorType", procState);
+                tp.m_map["errorType"] = procState;
                 if (targetURL)
-                    mlp.insert("requestURL", targetURL);
-                return make_pair(true,m_priv->sendError(this,"metadata", mlp));
+                    tp.m_map["requestURL"] = targetURL;
+                return make_pair(true,m_priv->sendError(this, "metadata", tp));
             }
         }
+        throw;
     }
-    catch (SAMLException& e) {
-        mlp.insert(e);
+    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));
     }
 #ifndef _DEBUG
     catch (...) {
-        mlp.insert("errorText", "Caught an unknown exception.");
+        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));
     }
 #endif
-
-    // If we get here then we've got an error.
-    mlp.insert("errorType", procState);
-
-    if (targetURL)
-        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
-
-    return make_pair(true,m_priv->sendError(this,"session", mlp));
 }
 
 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
 {
 #ifdef _DEBUG
-    saml::NDC ndc("doCheckAuthZ");
+    xmltooling::NDC ndc("doCheckAuthZ");
 #endif
 
-    ShibMLP mlp;
+    ExtTemplateParameters tp;
     const char* procState = "Authorization Processing Error";
     const char* targetURL = m_url.c_str();
 
@@ -437,9 +464,9 @@ pair<bool,void*> ShibTarget::doCheckAuthZ(void)
 #ifdef HAVE_STRCASECMP
                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
 #else
-                (!authType.first || stricmp(authType.second,"shibboleth")))
+                (!authType.first || _stricmp(authType.second,"shibboleth")))
 #endif
-            return pair<bool,void*>(true,returnDecline());
+            return make_pair(true,returnDecline());
 
         // Do we have an access control plugin?
         if (m_priv->m_settings.second) {
@@ -450,15 +477,14 @@ pair<bool,void*> ShibTarget::doCheckAuthZ(void)
                        const char *session_id = getCookie(shib_cookie.first);
                    try {
                                if (session_id && *session_id) {
-                                   m_priv->m_conf->getListener()->sessionGet(
-                                       m_priv->m_app,
-                                       session_id,
-                                       m_remote_addr.c_str(),
-                                       &m_priv->m_cacheEntry
-                                       );
+                        m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
+                            session_id,
+                            m_priv->m_app,
+                            m_remote_addr.c_str()
+                            );
                                }
                    }
-                   catch (SAMLException&) {
+                   catch (exception&) {
                        log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
                    }
                }
@@ -467,43 +493,43 @@ pair<bool,void*> ShibTarget::doCheckAuthZ(void)
             if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
                 // Let the caller decide how to proceed.
                 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
-                return pair<bool,void*>(false,NULL);
+                return make_pair(false,(void*)NULL);
             }
             else {
                 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
                 if (targetURL)
-                    mlp.insert("requestURL", targetURL);
-                return make_pair(true,m_priv->sendError(this, "access", mlp));
+                    tp.m_map["requestURL"] = targetURL;
+                return make_pair(true,m_priv->sendError(this, "access", tp));
             }
         }
         else
             return make_pair(true,returnDecline());
     }
-    catch (SAMLException& e) {
-        mlp.insert(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));
     }
 #ifndef _DEBUG
     catch (...) {
-        mlp.insert("errorText", "Caught an unknown exception.");
+        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));
     }
 #endif
-
-    // If we get here then we've got an error.
-    mlp.insert("errorType", procState);
-
-    if (targetURL)
-        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
-
-    return make_pair(true,m_priv->sendError(this, "access", mlp));
 }
 
 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
 {
 #ifdef _DEBUG
-    saml::NDC ndc("doExportAssertions");
+    xmltooling::NDC ndc("doExportAssertions");
 #endif
 
-    ShibMLP mlp;
+    ExtTemplateParameters tp;
     const char* procState = "Attribute Processing Error";
     const char* targetURL = m_url.c_str();
 
@@ -518,15 +544,14 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
                const char *session_id = getCookie(shib_cookie.first);
             try {
                        if (session_id && *session_id) {
-                           m_priv->m_conf->getListener()->sessionGet(
-                               m_priv->m_app,
-                               session_id,
-                               m_remote_addr.c_str(),
-                               &m_priv->m_cacheEntry
-                               );
+                    m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
+                        session_id,
+                        m_priv->m_app,
+                        m_remote_addr.c_str()
+                        );
                        }
             }
-            catch (SAMLException&) {
+            catch (exception&) {
                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)
@@ -537,36 +562,22 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
                // Still no data?
         if (!m_priv->m_cacheEntry) {
                if (requireSession)
-                       throw InvalidSessionException("Unable to obtain session information for request.");
+                       throw RetryableProfileException("Unable to obtain session information for request.");
                else
-                       return pair<bool,void*>(false,NULL);    // just bail silently
-        }
-
-        // Get the AAP providers, which contain the attribute policy info.
-        Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
-
-        // Clear out the list of mapped attributes
-        while (provs.hasNext()) {
-            IAAP* aap=provs.next();
-            Locker locker(aap);
-            Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
-            while (rules.hasNext()) {
-                const char* header=rules.next()->getHeader();
-                if (header)
-                    clearHeader(header);
-            }
+                       return make_pair(false,(void*)NULL);    // just bail silently
         }
         
-        ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
+        // 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);
 
-        // Maybe export the response.
-        clearHeader("Shib-Attributes");
+        // Maybe export the tokens.
         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
-        if (exp.first && exp.second && cr.unfiltered) {
-            ostringstream os;
-            os << *cr.unfiltered;
+        if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
             unsigned int outlen;
-            XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
+            XMLByte* serialized =
+                Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);
             XMLByte *pos, *pos2;
             for (pos=serialized, pos2=serialized; *pos2; pos2++)
                 if (isgraph(*pos2))
@@ -575,27 +586,24 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
             XMLString::release(&serialized);
         }
-    
+
         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
-        clearHeader("Shib-Origin-Site");
-        clearHeader("Shib-Identity-Provider");
-        clearHeader("Shib-Authentication-Method");
-        clearHeader("Shib-NameIdentifier-Format");
         setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
         setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
-        auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
-        setHeader("Shib-Authentication-Method", am.get());
+        setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
         
+        // Get the AAP providers, which contain the attribute policy info.
+        Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
+
         // Export NameID?
-        provs.reset();
         while (provs.hasNext()) {
             IAAP* aap=provs.next();
             Locker locker(aap);
-            const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
+            const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
             const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
             if (rule && rule->getHeader()) {
                 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
-                auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
+                auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());
                 setHeader("Shib-NameIdentifier-Format", form.get());
                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
                     setRemoteUser(nameid.get());
@@ -604,11 +612,10 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
             }
         }
         
-        clearHeader("Shib-Application-ID");
         setHeader("Shib-Application-ID", m_priv->m_app->getId());
     
         // Export the attributes.
-        Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
+        Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));
         while (a_iter.hasNext()) {
             SAMLAssertion* assert=a_iter.next();
             Iterator<SAMLStatement*> statements=assert->getStatements();
@@ -656,24 +663,40 @@ pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
             }
         }
     
-        return pair<bool,void*>(false,NULL);
+        return make_pair(false,(void*)NULL);
     }
-    catch (SAMLException& e) {
-        mlp.insert(e);
+    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));
     }
 #ifndef _DEBUG
     catch (...) {
-        mlp.insert("errorText", "Caught an unknown exception.");
+        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));
     }
 #endif
+}
 
-    // If we get here then we've got an error.
-    mlp.insert("errorType", procState);
-
-    if (targetURL)
-        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
+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 make_pair(true,m_priv->sendError(this, "rm", mlp));
+    return (bounds.first==bounds.second) ? NULL : bounds.first->second;
 }
 
 const char* ShibTarget::getCookie(const string& name) const
@@ -711,7 +734,7 @@ pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) cons
 {
     static const char* defProps="; path=/";
     
-    const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
+    const PropertySet* 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)
@@ -736,7 +759,7 @@ string ShibTarget::getHandlerURL(const char* resource) const
 
     bool ssl_only=false;
     const char* handler=NULL;
-    const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
+    const PropertySet* props=m_priv->m_app->getPropertySet("Sessions");
     if (props) {
         pair<bool,bool> p=props->getBool("handlerSSL");
         if (p.first)
@@ -750,7 +773,7 @@ string ShibTarget::getHandlerURL(const char* resource) const
     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())
+            xmltooling::params(2, handler ? handler : "null", m_priv->m_app->getId())
             );
 
     // The "handlerURL" property can be in one of three formats:
@@ -799,7 +822,7 @@ string ShibTarget::getHandlerURL(const char* resource) const
         colon += 3;      // Get past the ://
         slash = strchr(colon, '/');
     }
-    string host(colon, slash-colon);
+    string host(colon, (slash ? slash-colon : strlen(colon)));
 
     // Build the handler URL
     m_priv->m_handlerURL+=host + path;
@@ -836,12 +859,12 @@ 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) {}
+ShibTargetPriv::ShibTargetPriv()
+    : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL), m_cgiParser(NULL) {}
 
 ShibTargetPriv::~ShibTargetPriv()
 {
@@ -860,6 +883,7 @@ ShibTargetPriv::~ShibTargetPriv()
         m_conf = NULL;
     }
 
+    delete m_cgiParser;
     m_app = NULL;
     m_Config = NULL;
 }
@@ -904,22 +928,26 @@ void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, con
   st->m_url += uri;
 }
 
-void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
+void* ShibTargetPriv::sendError(
+    ShibTarget* 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")
         };
     
-    const IPropertySet* props=m_app->getPropertySet("Errors");
+    TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
+    const PropertySet* props=m_app->getPropertySet("Errors");
     if (props) {
         pair<bool,const char*> p=props->getString(page);
         if (p.first) {
             ifstream infile(p.second);
-            if (!infile.fail()) {
-                const char* res = mlp.run(infile,props);
-                if (res)
-                    return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
+            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));
             }
         }
         else if (!strcmp(page,"access"))
@@ -935,22 +963,122 @@ void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
         );
 }
 
-pair<bool,void*> ShibTargetPriv::dispatch(
-    ShibTarget* st,
-    const IPropertySet* config,
-    bool isHandler,
-    const char* forceType
-    ) const
+void ShibTargetPriv::clearHeaders(ShibTarget* st)
 {
-    pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
-    if (binding.first) {
-        auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
-        IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
-        if (!handler)
-            throw UnsupportedProfileException(
-                "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
-                );
-        return handler->run(st,config,isHandler);
+    // 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");
+
+    // Clear out the list of mapped attributes
+    Iterator<IAAP*> provs=m_app->getAAPProviders();
+    while (provs.hasNext()) {
+        IAAP* aap=provs.next();
+        Locker locker(aap);
+        Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
+        while (rules.hasNext()) {
+            const char* header=rules.next()->getHeader();
+            if (header)
+                st->clearHeader(header);
+        }
     }
-    throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");
+}
+
+/*************************************************************************
+ * 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] = ' ';
 }