Added redirectToSSL option to block non-SSL access.
[shibboleth/sp.git] / shib-target / shib-target.cpp
index 0246863..b9cc63e 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 <stdexcept>
 
 #include <shib/shib-threads.h>
-#include <log4cpp/Category.hh>
-#include <log4cpp/PropertyConfigurator.hh>
 #include <xercesc/util/Base64.hpp>
-#include <xercesc/util/regx/RegularExpression.hpp>
 
 #ifndef HAVE_STRCASECMP
 # define strcasecmp stricmp
@@ -83,62 +47,49 @@ using namespace shibtarget;
 using namespace log4cpp;
 
 namespace shibtarget {
-  class CgiParse
-  {
-  public:
-    CgiParse(const char* data, unsigned int len);
-    ~CgiParse();
-    const char* get_value(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);
-    char x2c(char *what);
-    void url_decode(char *url);
-
-    map<string,char*> kvp_map;
-  };
-
-  class ShibTargetPriv
-  {
-  public:
-    ShibTargetPriv();
-    ~ShibTargetPriv();
-
-    string url_encode(const char* s);
-    void get_application(const string& protocol, const string& hostname, int port, const string& uri);
-    void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
-    const char *getSessionId(ShibTarget* st);
-
-    IRequestMapper::Settings m_settings;
-    const IApplication *m_app;
-    string m_cookieName;
-    string m_shireURL;
-    string m_authnRequest;
-
-    const char *session_id;
-    string m_cookies;
-
-    ShibProfile m_sso_profile;
-    string m_provider_id;
-    SAMLAuthenticationStatement* m_sso_statement;
-    SAMLResponse* m_pre_response;
-    SAMLResponse* m_post_response;
+    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 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);
+        void clearHeaders(ShibTarget* st);
     
-    // These are the actual request parameters set via the init method.
-    string m_url;
-    string m_method;
-    string m_protocol;
-    string m_content_type;
-    string m_remote_addr;
-
-    ShibTargetConfig* m_Config;
-
-  private:
-    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;
+    };
 }
 
 
@@ -146,786 +97,671 @@ 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(ShibTargetConfig *config,
-                     string protocol, string hostname, int port,
-                     string uri, string content_type, string remote_host,
-                     string method)
+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
-  saml::NDC ndc("ShibTarget::init");
+    saml::NDC ndc("init");
 #endif
 
-  if (m_priv->m_app)
-    throw runtime_error("ShibTarget Already Initialized");
-  if (!config)
-    throw runtime_error("config is NULL.  Oops.");
-
-  m_priv->m_protocol = protocol;
-  m_priv->m_content_type = content_type;
-  m_priv->m_remote_addr = remote_host;
-  m_priv->m_Config = config;
-  m_priv->m_method = method;
-  m_priv->get_application(protocol, hostname, port, uri);
+    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 requireSessionFlag, bool handleProfile)
+
+pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
 {
 #ifdef _DEBUG
-  saml::NDC ndc("ShibTarget::doCheckAuthN");
+    saml::NDC ndc("doCheckAuthN");
 #endif
 
-  const char *targetURL = NULL;
-  const char *procState = "Process Initialization Error";
-  ShibMLP mlp;
-
-  try {
-    if (! m_priv->m_app)
-      throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized.  Application did not supply request information.");
+    const char* procState = "Request Processing Error";
+    const char* targetURL = m_url.c_str();
+    ShibMLP mlp;
 
-    targetURL = m_priv->m_url.c_str();
-    const char *shireURL = getShireURL(targetURL);
-    if (! shireURL)
-      throw ShibTargetException(SHIBRPC_OK, "Cannot map target URL to Shire URL.  Check configuration");
-
-    if (strstr(targetURL,shireURL)) {
-      if (handleProfile)
-        return doHandleProfile();
-      else
-        return pair<bool,void*>(true, returnOK());
-    }
-
-    string auth_type = getAuthType();
-    if (strcasecmp(auth_type.c_str(),"shibboleth"))
-      return pair<bool,void*>(true,returnDecline());
+    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 {
+                    mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
+                    return make_pair(true,m_priv->sendError(this,"ssl", mlp));
+                }
+            }
+        }
+        
+        string hURL = getHandlerURL(targetURL);
+        const char* handlerURL=hURL.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 (handler)
+                return doHandler();
+            else
+                return pair<bool,void*>(true, returnOK());
+        }
 
-    pair<bool,bool> requireSession =
-      m_priv->m_settings.first->getBool("requireSession");
-    if (!requireSession.first || !requireSession.second)
-      if (requireSessionFlag)
-       requireSession.second=true;
+        // 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");
+
+        // 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
+        // ShibBasicHijack is on, but that's up to it.
+        if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
+#ifdef HAVE_STRCASECMP
+                (!authType.first || strcasecmp(authType.second,"shibboleth")))
+#else
+                (!authType.first || _stricmp(authType.second,"shibboleth")))
+#endif
+            return pair<bool,void*>(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());
+
+            // No cookie, but we require a session. Initiate a new session using the indicated method.
+            procState = "Session Initiator Error";
+            const IHandler* initiator=NULL;
+            if (requireSessionWith.first) {
+                initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
+                if (!initiator)
+                    throw ConfigurationException(
+                        "No session initiator found with id ($1), check requireSessionWith command.",
+                        params(1,requireSessionWith.second)
+                        );
+            }
+            else {
+                initiator=m_priv->m_app->getDefaultSessionInitiator();
+                if (!initiator)
+                    throw ConfigurationException("No default session initiator found, check configuration.");
+            }
 
-    const char *session_id = m_priv->getSessionId(this);
-    
-    if (!session_id || !*session_id) {
-      // No session.  Maybe that's acceptable?
+            return initiator->run(this,false);
+        }
 
-      if (!requireSession.second)
-        return pair<bool,void*>(true,returnOK());
+        procState = "Session Processing Error";
+        try {
+            m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
+                session_id,
+                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 InvalidSessionException("Session no longer valid.");
+        }
+        catch (SAMLException& e) {
+            log(LogLevelError, string("session processing failed: ") + e.what());
+
+            // If no session is required, bail now.
+            if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
+                // Has to be OK because DECLINED will just cause Apache
+                // 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());
+
+            // Try and cast down.
+            SAMLException* 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;
+                if (requireSessionWith.first) {
+                    initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
+                    if (!initiator)
+                        throw ConfigurationException(
+                            "No session initiator found with id ($1), check requireSessionWith command.",
+                            params(1,requireSessionWith.second)
+                            );
+                }
+                else {
+                    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
+        }
 
-      // No cookie, but we require a session.  Generate an AuthnRequest.
-      return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
+        // 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);
     }
-
-    procState = "Session Processing Error";
-    RPCError* status = sessionGet(
-        session_id,
-        m_priv->m_remote_addr.c_str(),
-        m_priv->m_sso_profile,
-        m_priv->m_provider_id,
-        &m_priv->m_sso_statement,
-        &m_priv->m_pre_response,
-        &m_priv->m_post_response
-        );
-
-    if (status->isError()) {
-
-      // If no session is required, bail now.
-      if (!requireSession.second)
-        return pair<bool,void*>(true, returnOK());
-                   // XXX: Or should this be DECLINED?
-                   // Has to be OK because DECLINED will just cause Apache
-                   // 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.
-      else if (status->isRetryable()) {
-        // Session is invalid but we can retry the auth -- generate an AuthnRequest
-        delete status;
-        return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
-
-      } else {
-        string er = "Unretryable error: " ;
-        er += status->getText();
-        log(LogLevelError, er);
-        mlp.insert(*status);
-        delete status;
-        goto out;
-      }
-
-      delete status;
+    catch (SAMLException& e) {
+        mlp.insert(e);
     }
-
-    // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
-    // Let the caller decide how to proceed.
-    log(LogLevelInfo, "doCheckAuthN Succeeded\n");
-    return pair<bool,void*>(false,NULL);
-
-  } catch (ShibTargetException &e) {
-    mlp.insert("errorText", e.what());
-
 #ifndef _DEBUG
-  } catch (...) {
-    mlp.insert("errorText", "Unexpected Exception");
+    catch (...) {
+        mlp.insert("errorText", "Caught an unknown exception.");
+    }
 #endif
-  }
-
-  // If we get here then we've got an error.
-  mlp.insert("errorType", procState);
-  mlp.insert("errorDesc", "An error occurred while processing your request.");
 
- out:
-  if (targetURL)
-    mlp.insert("requestURL", targetURL);
+    // 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));
+    return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
 }
 
-pair<bool,void*>
-ShibTarget::doHandleProfile(void)
+pair<bool,void*> ShibTarget::doHandler(void)
 {
 #ifdef _DEBUG
-  saml::NDC ndc("ShibTarget::doHandleProfile");
+    saml::NDC ndc("doHandler");
 #endif
 
-  const char *targetURL = NULL;
-  const char *procState = "Session Creation Service Error";
-  ShibMLP mlp;
-
-  try {
-    if (! m_priv->m_app)
-      throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized.  Application did not supply request information.");
-
-    targetURL = m_priv->m_url.c_str();
-    const char *shireURL = getShireURL(targetURL);
-
-    if (!shireURL)
-      throw ShibTargetException(SHIBRPC_OK, "doHandleProfile() unable to map request to a proper shireURL setting.  Check Configuration.");
+    const char* procState = "Shibboleth Handler Error";
+    const char* targetURL = m_url.c_str();
+    ShibMLP mlp;
 
+    try {
+        if (!m_priv->m_app)
+            throw ConfigurationException("System uninitialized, application did not supply request information.");
 
-    // Make sure we only process the SHIRE requests.
-    if (!strstr(targetURL, shireURL))
-      return pair<bool,void*>(true, returnDecline());
+        string hURL = getHandlerURL(targetURL);
+        const char* handlerURL=hURL.c_str();
+        if (!handlerURL)
+            throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
 
-    const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
-    if (!sessionProps)
-      throw ShibTargetException(SHIBRPC_OK, "doHandleProfile() unable to map request to application session settings.  Check configuration");
+        // Make sure we only process handler requests.
+        if (!strstr(targetURL,handlerURL))
+            return pair<bool,void*>(true, returnDecline());
 
-    // this always returns something
-    pair<const char*,const char*> shib_cookie=getCookieNameProps();
+        const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
+        if (!sessionProps)
+            throw ConfigurationException("Unable to map request to application session settings, check configuration.");
 
-    // Process SHIRE request
-      
-    pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
+        // Process incoming request.
+        pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
       
-    // Make sure this is SSL, if it should be
-    if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol == "https")
-      throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
-
-    // If this is a GET, we see if it's a lazy session request, otherwise
-    // assume it's a profile response and process it.
-    string cgistr;
-    if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
-      cgistr = getArgs();
-      const char* areq=cgistr.empty() ? NULL : getLazyAuthnRequest(cgistr.c_str());
-      if (areq)
-        return pair<bool,void*>(true, sendRedirect(areq));
+        // 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.");
+
+        // 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).
+        pair<bool,void*> hret;
+        Iterator<const IHandler*> handlers=m_priv->m_app->getHandlers(targetURL + strlen(handlerURL));
+
+        if (handlers.size()==0)
+            throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
+
+        while (handlers.hasNext()) {
+            const IHandler* handler=handlers.next();
+
+            if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService)))
+                procState = "Session Creation Error";
+            else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
+                procState = "Session Initiator Error";
+            else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService)))
+                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";
+            hret=handler->run(this);
+
+            // Did the handler run successfully?
+            if (hret.first)
+                return hret;
+        }
+        
+        throw SAMLException("Configured Shibboleth handler(s) failed to fully process the request.");
     }
-    else if (!strcasecmp(m_priv->m_method.c_str(), "POST")) {
-        if (m_priv->m_content_type.empty() || strcasecmp(m_priv->m_content_type.c_str(),"application/x-www-form-urlencoded")) {
-            string er = string("blocked invalid POST content-type to session creation service: ") + m_priv->m_content_type;
-            throw ShibTargetException(SHIBRPC_OK, er.c_str());
+    catch (MetadataException& e) {
+        mlp.insert(e);
+        // See if a metadata error page is installed.
+        const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
+        if (props) {
+            pair<bool,const char*> p=props->getString("metadata");
+            if (p.first) {
+                mlp.insert("errorType", procState);
+                if (targetURL)
+                    mlp.insert("requestURL", targetURL);
+                return make_pair(true,m_priv->sendError(this,"metadata", mlp));
+            }
         }
-        // Read the POST Data
-        cgistr = getPostData();
     }
-       
-    // process the submission
-    string cookie,target,statemgr_packet;
-    RPCError* status = sessionNew(
-        SAML_11_POST | SAML_11_ARTIFACT,
-        cgistr.c_str(),
-        NULL,   // XXX: no state token yet
-        m_priv->m_remote_addr.c_str(),
-        cookie,
-        target,
-        statemgr_packet
-        );
-
-    if (status->isError()) {
-      char buf[25];
-      sprintf(buf, "(%d): ", status->getCode());
-      string er = string("doHandleProfile() profile processing failed ") + buf + status->getText();
-      log(LogLevelError, er);
-
-      if (status->isRetryable()) {
-        delete status;
-        return pair<bool,void*>(true, sendRedirect(getAuthnRequest(target.c_str())));
-      }
-
-      // return this error to the user.
-      mlp.insert(*status);
-      delete status;
-      goto out;
+    catch (SAMLException& e) {
+        mlp.insert(e);
     }
-    delete status;
-
-    log(LogLevelDebug, string("doHandleProfile() profile processing succeeded, new session(") + cookie + ")");
-
-    // We've got a good session, set the cookie...
-    cookie += shib_cookie.second;
-    setCookie(shib_cookie.first, cookie);
-
-    // ... and redirect to the target
-    return pair<bool,void*>(true, sendRedirect(target));
-
-  } catch (ShibTargetException &e) {
-    mlp.insert("errorText", e.what());
-
 #ifndef _DEBUG
-  } catch (...) {
-    mlp.insert("errorText", "Unexpected Exception");
+    catch (...) {
+        mlp.insert("errorText", "Caught an unknown exception.");
+    }
 #endif
-  }
 
-  // If we get here then we've got an error.
-  mlp.insert("errorType", procState);
-  mlp.insert("errorDesc", "An error occurred while processing your request.");
+    // If we get here then we've got an error.
+    mlp.insert("errorType", procState);
 
- out:
-  if (targetURL)
-    mlp.insert("requestURL", targetURL);
+    if (targetURL)
+        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
 
-  return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
+    return make_pair(true,m_priv->sendError(this,"session", mlp));
 }
 
-pair<bool,void*>
-ShibTarget::doCheckAuthZ(void)
+pair<bool,void*> ShibTarget::doCheckAuthZ(void)
 {
 #ifdef _DEBUG
-  saml::NDC ndc("ShibTarget::doCheckAuthZ");
+    saml::NDC ndc("doCheckAuthZ");
 #endif
 
-  ShibMLP mlp;
-  const char *procState = "Authorization Processing Error";
-  const char *targetURL = NULL;
-  HTAccessInfo *ht = NULL;
-  HTGroupTable* grpstatus = NULL;
-
-  try {
-    if (! m_priv->m_app)
-      throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized.  Application did not supply request information.");
-
-    targetURL = m_priv->m_url.c_str();
-    const char *session_id = m_priv->getSessionId(this);
-
-    // Do we have an access control plugin?
-    if (m_priv->m_settings.second) {
-      Locker acllock(m_priv->m_settings.second);
-      if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
-            m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*))) {
-        log(LogLevelError, "doCheckAuthZ: access control provider denied access");
-        goto out;
-      }
-    }
-
-    // Perform HTAccess Checks
-    ht = getAccessInfo();
-
-    // No Info means OK.  Just return
-    if (!ht)
-      return pair<bool,void*>(false, NULL);
-
-    vector<bool> auth_OK(ht->elements.size(), false);
-    bool method_restricted=false;
-    string remote_user = getRemoteUser();
-
-    #define CHECK_OK do { \
-      if (ht->requireAll) { \
-        delete ht; \
-        if (grpstatus) delete grpstatus; \
-        return pair<bool,void*>(false, NULL); \
-      } \
-      auth_OK[x] = true; \
-      continue; \
-    } while (0)
-
-    for (int x = 0; x < ht->elements.size(); x++) {
-      auth_OK[x] = false;
-      HTAccessInfo::RequireLine *line = ht->elements[x];
-      if (! line->use_line)
-        continue;
-      method_restricted = true;
-
-      const char *w = line->tokens[0].c_str();
-
-      if (!strcasecmp(w,"Shibboleth")) {
-        // This is a dummy rule needed because Apache conflates authn and authz.
-        // Without some require rule, AuthType is ignored and no check_user hooks run.
-        CHECK_OK;
-      }
-      else if (!strcmp(w,"valid-user")) {
-        log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
-        CHECK_OK;
-      }
-      else if (!strcmp(w,"user") && !remote_user.empty()) {
-        bool regexp=false;
-        for (int i = 1; i < line->tokens.size(); i++) {
-          w = line->tokens[i].c_str();
-          if (*w == '~') {
-            regexp = true;
-            continue;
-          }
-                
-          if (regexp) {
-            try {
-              // To do regex matching, we have to convert from UTF-8.
-              auto_ptr<XMLCh> trans(fromUTF8(w));
-              RegularExpression re(trans.get());
-              auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
-              if (re.matches(trans2.get())) {
-                log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
-                CHECK_OK;
-              }
-            }
-            catch (XMLException& ex) {
-              auto_ptr_char tmp(ex.getMessage());
-              log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
-                 + w + "): " + tmp.get());
-            }
-          }
-          else if (!strcmp(remote_user.c_str(), w)) {
-            log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
-            CHECK_OK;
-          }
-        }
-      }
-      else if (!strcmp(w,"group")) {
-        grpstatus = getGroupTable(remote_user);
-
-        if (!grpstatus) {
-          delete ht;
-          return pair<bool,void*>(true, returnDecline());
-        }
-    
-        for (int i = 1; i < line->tokens.size(); i++) {
-          w = line->tokens[i].c_str();
-          if (grpstatus->lookup(w)) {
-            log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
-            CHECK_OK;
-          }
-        }
-        delete grpstatus;
-        grpstatus = NULL;
-      }
-      else {
-        Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
-        AAP wrapper(provs, w);
-        if (wrapper.fail()) {
-          log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
-          continue;
-        }
-
-        bool regexp = false;
-        string vals = getHeader(wrapper->getHeader());
-        for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
-          w = line->tokens[i].c_str();
-          if (*w == '~') {
-            regexp = true;
-            continue;
-          }
-
-          try {
-            auto_ptr<RegularExpression> re;
-            if (regexp) {
-              delete re.release();
-              auto_ptr<XMLCh> trans(fromUTF8(w));
-              auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
-              re=temp;
-            }
-                    
-            string vals_str(vals);
-            int j = 0;
-            for (int i = 0;  i < vals_str.length();  i++) {
-              if (vals_str.at(i) == ';') {
-                if (i == 0) {
-                  log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
-                    vals + ": starts with a semicolon");
-                  goto out;
-                }
-
-                if (vals_str.at(i-1) == '\\') {
-                  vals_str.erase(i-1, 1);
-                  i--;
-                  continue;
-                }
+    ShibMLP mlp;
+    const char* procState = "Authorization Processing Error";
+    const char* targetURL = m_url.c_str();
 
-                string val = vals_str.substr(j, i-j);
-                j = i+1;
-                if (regexp) {
-                  auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
-                  if (re->matches(trans.get())) {
-                    log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-                       ", got " + val + ": authorization granted");
-                    CHECK_OK;
-                  }
-                }
-                else if ((wrapper->getCaseSensitive() && val==w) ||
-                 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
-                  log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-                  ", got " + val + ": authorization granted.");
-                  CHECK_OK;
-                }
-                else {
-                    log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-                        ", got " + val + ": authoritzation not granted.");
-                }
-              }
-            }
-    
-            string val = vals_str.substr(j, vals_str.length()-j);
-            if (regexp) {
-              auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
-              if (re->matches(trans.get())) {
-                log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-                    ", got " + val + ": authorization granted.");
-                CHECK_OK;
-              }
-            }
-            else if ((wrapper->getCaseSensitive() && val==w) ||
-                    (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
-              log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-              ", got " + val + ": authorization granted");
-              CHECK_OK;
+    try {
+        if (!m_priv->m_app)
+            throw ConfigurationException("System uninitialized, application did not supply request information.");
+
+        // 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");
+
+        // 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
+        // ShibBasicHijack is on, but that's up to it.
+        if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
+#ifdef HAVE_STRCASECMP
+                (!authType.first || strcasecmp(authType.second,"shibboleth")))
+#else
+                (!authType.first || _stricmp(authType.second,"shibboleth")))
+#endif
+            return pair<bool,void*>(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");
+                   }
+               }
+       
+            Locker acllock(m_priv->m_settings.second);
+            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);
             }
             else {
-              log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
-              ", got " + val + ": authorization not granted");
+                log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
+                if (targetURL)
+                    mlp.insert("requestURL", targetURL);
+                return make_pair(true,m_priv->sendError(this, "access", mlp));
             }
-          }
-          catch (XMLException& ex) {
-            auto_ptr_char tmp(ex.getMessage());
-            log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
-                + w + "): " + tmp.get());
-          }
         }
-      }
-    } // for x
-
-
-    // check if all require directives are true
-    bool auth_all_OK = true;
-    for (int i = 0; i < ht->elements.size(); i++) {
-        auth_all_OK &= auth_OK[i];
+        else
+            return make_pair(true,returnDecline());
+    }
+    catch (SAMLException& e) {
+        mlp.insert(e);
     }
-
-    delete ht;
-    if (grpstatus) delete grpstatus;
-    if (auth_all_OK || !method_restricted)
-      return pair<bool,void*>(false, NULL);
-
-    // If we get here there's an access error, so just fall through
-
-  } catch (ShibTargetException &e) {
-    mlp.insert("errorText", e.what());
-
 #ifndef _DEBUG
-  } catch (...) {
-    mlp.insert("errorText", "Unexpected Exception");
+    catch (...) {
+        mlp.insert("errorText", "Caught an unknown exception.");
+    }
 #endif
-  }
-
-  // If we get here then we've got an error.
-  mlp.insert("errorType", procState);
-  mlp.insert("errorDesc", "An error occurred while processing your request.");
 
- out:
-  if (targetURL)
-    mlp.insert("requestURL", targetURL);
+    // If we get here then we've got an error.
+    mlp.insert("errorType", procState);
 
-  if (ht)
-    delete ht;
+    if (targetURL)
+        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
 
-  return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
+    return make_pair(true,m_priv->sendError(this, "access", mlp));
 }
 
-pair<bool,void*>
-ShibTarget::doExportAssertions(bool exportAssertion)
+pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
 {
 #ifdef _DEBUG
-  saml::NDC ndc("ShibTarget::doExportAssertions");
+    saml::NDC ndc("doExportAssertions");
 #endif
 
-  ShibMLP mlp;
-  const char *procState = "Attribute Processing Error";
-  const char *targetURL = NULL;
-  char *page = "rm";
-
-  try {
-    if (! m_priv->m_app)
-      throw ShibTargetException(SHIBRPC_OK, "ShibTarget Uninitialized.  Application did not supply request information.");
-
-    targetURL = m_priv->m_url.c_str();
-    const char *session_id = m_priv->getSessionId(this);
-
-    if (!m_priv->m_sso_statement) {
-        // 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.
-        RPCError* status = sessionGet(
-            session_id,
-            m_priv->m_remote_addr.c_str(),
-            m_priv->m_sso_profile,
-            m_priv->m_provider_id,
-            &m_priv->m_sso_statement,
-            &m_priv->m_pre_response,
-            &m_priv->m_post_response
-            );
-        if (status->isError()) {
-            string er = "sessionGet failed: ";
-            er += status->getText();
-            log(ShibTarget::LogLevelError, er);
-            mlp.insert(*status);
-            delete status;
-            goto out;
-        }
-        delete status;
-    }
+    ShibMLP mlp;
+    const char* procState = "Attribute Processing Error";
+    const char* targetURL = m_url.c_str();
 
-    // 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);
-      }
-    }
-    
-    // Maybe export the first assertion.
-    clearHeader("Shib-Attributes");
-    pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
-    if (!exp.first || !exp.second)
-      if (exportAssertion)
-        exp.second=true;
-    if (exp.second && m_priv->m_pre_response) {
-      ostringstream os;
-      os << *(m_priv->m_pre_response);
-      unsigned int outlen;
-      char* resp = (char*)os.str().c_str();
-      XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(resp), os.str().length(), &outlen);
-      setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
-      XMLString::release(&serialized);
-    }
+    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;
+            }
+        }
 
-    // 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_provider_id.c_str());
-    setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
-    auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
-    setHeader("Shib-Authentication-Method", am.get());
-    
-    // Export NameID?
-    provs.reset();
-    while (provs.hasNext()) {
-        IAAP* aap=provs.next();
-        Locker locker(aap);
-        const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
-        if (rule && rule->getHeader()) {
-          auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
-          auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
-          setHeader("Shib-NameIdentifier-Format", form.get());
-          if (!strcmp(rule->getHeader(),"REMOTE_USER"))
-            setRemoteUser(nameid.get());
-          else
-            setHeader(rule->getHeader(), nameid.get());
+               // Still no data?
+        if (!m_priv->m_cacheEntry) {
+               if (requireSession)
+                       throw InvalidSessionException("Unable to obtain session information for request.");
+               else
+                       return pair<bool,void*>(false,NULL);    // just bail silently
         }
-    }
-    
-    clearHeader("Shib-Application-ID");
-    setHeader("Shib-Application-ID", m_priv->m_app->getId());
-
-    // Export the attributes.
-    Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
-    while (a_iter.hasNext()) {
-      SAMLAssertion* assert=a_iter.next();
-      Iterator<SAMLStatement*> statements=assert->getStatements();
-      while (statements.hasNext()) {
-        SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
-        if (!astate)
-            continue;
-        Iterator<SAMLAttribute*> attrs=astate->getAttributes();
-        while (attrs.hasNext()) {
-          SAMLAttribute* attr=attrs.next();
         
-          // Are we supposed to export it?
-          provs.reset();
-          while (provs.hasNext()) {
+        // 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 tokens.
+        pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
+        if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
+            unsigned int 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))
+                    *pos++=*pos2;
+            *pos=0;
+            setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
+            XMLString::release(&serialized);
+        }
+
+        // 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());
+        
+        // Get the AAP providers, which contain the attribute policy info.
+        Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
+
+        // Export NameID?
+        while (provs.hasNext()) {
             IAAP* aap=provs.next();
             Locker locker(aap);
-            const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
-            if (!rule || !rule->getHeader()) {
-                continue;
+            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(sub.second->getNameIdentifier()->getName());
+                setHeader("Shib-NameIdentifier-Format", form.get());
+                if (!strcmp(rule->getHeader(),"REMOTE_USER"))
+                    setRemoteUser(nameid.get());
+                else
+                    setHeader(rule->getHeader(), nameid.get());
             }
-                
-            Iterator<string> vals=attr->getSingleByteValues();
-            if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
-                setRemoteUser(vals.next());
-            else {
-                int it=0;
-                string header = getHeader(rule->getHeader());
-                if (!header.empty())
-                  it++;
-                for (; vals.hasNext(); it++) {
-                  string value = vals.next();
-                  for (string::size_type pos = value.find_first_of(";", string::size_type(0));
-                  pos != string::npos;
-                  pos = value.find_first_of(";", pos)) {
-               value.insert(pos, "\\");
-               pos += 2;
-                  }
-                  if (it)
-               header += ";";
-                  header += value;
+        }
+        
+        setHeader("Shib-Application-ID", m_priv->m_app->getId());
+    
+        // Export the attributes.
+        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();
+            while (statements.hasNext()) {
+                SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
+                if (!astate)
+                    continue;
+                Iterator<SAMLAttribute*> attrs=astate->getAttributes();
+                while (attrs.hasNext()) {
+                    SAMLAttribute* attr=attrs.next();
+            
+                    // Are we supposed to export it?
+                    provs.reset();
+                    while (provs.hasNext()) {
+                        IAAP* aap=provs.next();
+                        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());
+                        else {
+                            int it=0;
+                            string header = getHeader(rule->getHeader());
+                            if (!header.empty())
+                                it++;
+                            for (; vals.hasNext(); it++) {
+                                string value = vals.next();
+                                for (string::size_type pos = value.find_first_of(";", string::size_type(0));
+                                        pos != string::npos;
+                                        pos = value.find_first_of(";", pos)) {
+                                    value.insert(pos, "\\");
+                                    pos += 2;
+                                }
+                                if (it)
+                                    header += ";";
+                                header += value;
+                            }
+                            setHeader(rule->getHeader(), header);
+                        }
+                    }
                 }
-                setHeader(rule->getHeader(), header);
             }
-          }
         }
-      }
+    
+        return pair<bool,void*>(false,NULL);
+    }
+    catch (SAMLException& e) {
+        mlp.insert(e);
     }
-
-    return pair<bool,void*>(false,NULL);
-
-  } catch (ShibTargetException &e) {
-    mlp.insert("errorText", e.what());
-
 #ifndef _DEBUG
-  } catch (...) {
-    mlp.insert("errorText", "Unexpected Exception");
+    catch (...) {
+        mlp.insert("errorText", "Caught an unknown exception.");
+    }
 #endif
 
-  }
-
-  // If we get here then we've got an error.
-  mlp.insert("errorType", procState);
-  mlp.insert("errorDesc", "An error occurred while processing your request.");
+    // If we get here then we've got an error.
+    mlp.insert("errorType", procState);
 
- out:
-  if (targetURL)
-    mlp.insert("requestURL", targetURL);
+    if (targetURL)
+        mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
 
-  return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
+    return make_pair(true,m_priv->sendError(this, "rm", mlp));
 }
 
+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++;
+    }
 
-// SHIRE APIs
+    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();
+}
 
-// Get the session cookie name and properties for the application
-std::pair<const char*,const char*>
-ShibTarget::getCookieNameProps() const
+pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
 {
     static const char* defProps="; path=/";
-    static const char* defName="_shibsession_";
     
-    // XXX: What to do if m_app isn't set?
-
-    const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
+    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;
-        if (!m_priv->m_cookieName.empty())
-            return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),
-                                                p.second);
         pair<bool,const char*> p2=props->getString("cookieName");
-        if (p2.first) {
-            m_priv->m_cookieName=p2.second;
-            return pair<const char*,const char*>(p2.second,p.second);
-        }
-        m_priv->m_cookieName=defName;
-        m_priv->m_cookieName+=m_priv->m_app->getId();
-        return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),p.second);
+        if (p2.first)
+            return make_pair(string(prefix) + p2.second,p.second);
+        return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
     }
-    m_priv->m_cookieName=defName;
-    m_priv->m_cookieName+=m_priv->m_app->getId();
-    return pair<const char*,const char*>(m_priv->m_cookieName.c_str(),defProps);
+    
+    // Shouldn't happen, but just in case..
+    return pair<string,const char*>(prefix,defProps);
 }
-        
-// Find the default assertion consumer service for the resource
-const char*
-ShibTarget::getShireURL(const char* resource) const
-{
-    if (!m_priv->m_shireURL.empty())
-        return m_priv->m_shireURL.c_str();
 
-    // XXX: what to do is m_app is NULL?
+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 shire_ssl_only=false;
-    const char* shire=NULL;
+    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("shireSSL");
+        pair<bool,bool> p=props->getBool("handlerSSL");
         if (p.first)
-            shire_ssl_only=p.second;
-        pair<bool,const char*> p2=props->getString("shireURL");
+            ssl_only=p.second;
+        pair<bool,const char*> p2=props->getString("handlerURL");
         if (p2.first)
-            shire=p2.second;
+            handler=p2.second;
     }
     
     // Should never happen...
-    if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
-        return NULL;
+    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 "shireURL" property can be in one of three formats:
+    // 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  shire     shire       shire
-    // 2  shire     resource    shire
-    // 3  resource  resource    shire
+    // 1  handler   handler     handler
+    // 2  handler   resource    handler
+    // 3  resource  resource    handler
     //
-    // note: if shire_ssl_only is true, make sure the protocol is https
+    // note: if ssl_only is true, make sure the protocol is https
 
     const char* path = NULL;
 
-    // Decide whether to use the shire or the resource for the "protocol"
+    // Decide whether to use the handler or the resource for the "protocol"
     const char* prot;
-    if (*shire != '/') {
-        prot = shire;
+    if (*handler != '/') {
+        prot = handler;
     }
     else {
         prot = resource;
-        path = shire;
+        path = handler;
     }
 
     // break apart the "protocol" string into protocol, host, and "the rest"
@@ -936,313 +772,79 @@ ShibTarget::getShireURL(const char* resource) const
         path = slash;
 
     // Compute the actual protocol and store in member.
-    if (shire_ssl_only)
-        m_priv->m_shireURL.assign("https://");
+    if (ssl_only)
+        m_priv->m_handlerURL.assign("https://");
     else
-        m_priv->m_shireURL.assign(prot, colon-prot);
+        m_priv->m_handlerURL.assign(prot, colon-prot);
 
     // create the "host" from either the colon/slash or from the target string
-    // If prot == shire then we're in either #1 or #2, else #3.
+    // If prot == handler then we're in either #1 or #2, else #3.
     // If slash == colon then we're in #2.
-    if (prot != shire || slash == colon) {
+    if (prot != handler || slash == colon) {
         colon = strchr(resource, ':');
         colon += 3;      // Get past the ://
         slash = strchr(colon, '/');
     }
     string host(colon, slash-colon);
 
-    // Build the shire URL
-    m_priv->m_shireURL+=host + path;
-    return m_priv->m_shireURL.c_str();
+    // Build the handler URL
+    m_priv->m_handlerURL+=host + path;
+    return m_priv->m_handlerURL;
 }
-        
-// Generate a Shib 1.x AuthnRequest redirect URL for the resource
-const char*
-ShibTarget::getAuthnRequest(const char* resource) const
-{
-    if (!m_priv->m_authnRequest.empty())
-        return m_priv->m_authnRequest.c_str();
-        
-    // XXX: what to do if m_app is NULL?
 
-    char timebuf[16];
-    sprintf(timebuf,"%u",time(NULL));
-    
-    const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
-    if (props) {
-        pair<bool,const char*> wayf=props->getString("wayfURL");
-        if (wayf.first) {
-            m_priv->m_authnRequest=m_priv->m_authnRequest + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) +
-                "&target=" + m_priv->url_encode(resource) + "&time=" + timebuf;
-            pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
-            if (!old.first || !old.second) {
-                wayf=m_priv->m_app->getString("providerId");
-                if (wayf.first)
-                    m_priv->m_authnRequest=m_priv->m_authnRequest + "&providerId=" + m_priv->url_encode(wayf.second);
-            }
-        }
-    }
-    return m_priv->m_authnRequest.c_str();
-}
-        
-// Process a lazy session setup request and turn it into an AuthnRequest
-const char*
-ShibTarget::getLazyAuthnRequest(const char* query_string) const
+void ShibTarget::log(ShibLogLevel level, const string& msg)
 {
-    CgiParse parser(query_string,strlen(query_string));
-    const char* target=parser.get_value("target");
-    if (!target || !*target)
-        return NULL;
-    return getAuthnRequest(target);
+    Category::getInstance("shibtarget.ShibTarget").log(
+        (level == LogLevelDebug ? Priority::DEBUG :
+        (level == LogLevelInfo ? Priority::INFO :
+        (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
+        msg
+    );
 }
-        
-RPCError* ShibTarget::sessionNew(
-    int supported_profiles,
-    const char* packet,
-    const char* statemgr_cookie,
-    const char* ip,
-    string& cookie,
-    string& target,
-    string& statemgr_packet
-    ) const
-{
-#ifdef _DEBUG
-  saml::NDC ndc("sessionNew");
-#endif
-  Category& log = Category::getInstance("shibtarget.ShibTarget");
 
-  if (!packet || !*packet) {
-    log.error("Empty profile content");
-    return new RPCError(SHIBRPC_RESPONSE_MISSING, "Empty profile content");
-  }
-
-  if (!ip || !*ip) {
-    log.error("Invalid IP address");
-    return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP address");
-  }
-  
-  if (supported_profiles <= 0) {
-    log.error("No profile support indicated");
-    return new RPCError(SHIBRPC_INTERNAL_ERROR, "No profile support indicated");
-  }
-  
-  shibrpc_new_session_args_2 arg;
-  arg.recipient = (char*) m_priv->m_shireURL.c_str();
-  arg.application_id = (char*) m_priv->m_app->getId();
-  arg.packet = (char*)packet;
-  arg.client_addr = (char*)ip;
-  arg.supported_profiles = supported_profiles;
-  if (statemgr_cookie)
-    arg.cookie = (char*)statemgr_cookie;
-  else
-    arg.cookie = "";
-
-  log.info("create session for user at (%s) for application (%s) with state token (%s)",
-    ip, arg.application_id, statemgr_cookie);
-
-  shibrpc_new_session_ret_2 ret;
-  memset(&ret, 0, sizeof(ret));
-
-  // Loop on the RPC in case we lost contact the first time through
-  int retry = 1;
-  CLIENT* clnt;
-  RPC rpc;
-  do {
-    clnt = rpc->connect();
-    clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
-    if (status != RPC_SUCCESS) {
-      // FAILED.  Release, disconnect, and retry
-      log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
-      rpc->disconnect();
-      if (retry)
-        retry--;
-      else
-        return new RPCError(-1, "RPC Failure");
-    }
-    else {
-      // SUCCESS.  Pool and continue
-      retry = -1;
-    }
-  } while (retry>=0);
-
-  log.debug("RPC completed with status %d (%p)", ret.status.status, this);
-
-  RPCError* retval;
-  if (ret.status.status)
-    retval = new RPCError(&ret.status);
-  else {
-    log.debug ("new session cookie: %s", ret.cookie);
-    cookie = ret.cookie;
-    if (ret.target)
-        target = ret.target;
-    if (ret.packet)
-        statemgr_packet = ret.packet;
-    retval = new RPCError();
-  }
-
-  clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
-  rpc.pool();
-
-  log.debug("returning");
-  return retval;
+const IApplication* ShibTarget::getApplication() const
+{
+    return m_priv->m_app;
 }
 
-RPCError* ShibTarget::sessionGet(
-    const char* cookie,
-    const char* ip,
-    ShibProfile& profile,
-    string& provider_id,
-    SAMLAuthenticationStatement** auth_statement,
-    SAMLResponse** attr_response_pre,
-    SAMLResponse** attr_response_post
-    ) const
+const IConfig* ShibTarget::getConfig() const
 {
-#ifdef _DEBUG
-  saml::NDC ndc("sessionGet");
-#endif
-  Category& log = Category::getInstance("shibtarget.ShibTarget");
-
-  if (!cookie || !*cookie) {
-    log.error("No cookie value was provided");
-    return new RPCError(SHIBRPC_NO_SESSION, "No cookie value was provided");
-  }
-  else if (strchr(cookie,'=')) {
-    log.error("The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
-    return new RPCError(SHIBRPC_INTERNAL_ERROR, "The cookie value wasn't extracted successfully, use a more unique cookie name for your installation.");
-  }
-
-  if (!ip || !*ip) {
-    log.error("Invalid IP Address");
-    return new RPCError(SHIBRPC_IPADDR_MISSING, "Invalid IP Address");
-  }
-
-  log.info("getting session for client at (%s)", ip);
-  log.debug("session cookie (%s)", cookie);
-
-  shibrpc_get_session_args_2 arg;
-
-  arg.cookie = (char*)cookie;
-  arg.client_addr = (char*)ip;
-  arg.application_id = (char*)m_priv->m_app->getId();
-
-  shibrpc_get_session_ret_2 ret;
-  memset (&ret, 0, sizeof(ret));
-
-  // Loop on the RPC in case we lost contact the first time through
-  int retry = 1;
-  CLIENT *clnt;
-  RPC rpc;
-  do {
-    clnt = rpc->connect();
-    clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
-    if (status != RPC_SUCCESS) {
-      // FAILED.  Release, disconnect, and try again...
-      log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
-      rpc->disconnect();
-      if (retry)
-          retry--;
-      else
-          return new RPCError(-1, "RPC Failure");
-    }
-    else {
-      // SUCCESS
-      retry = -1;
-    }
-  } while (retry>=0);
-
-  log.debug("RPC completed with status %d, %p", ret.status.status, this);
-
-  RPCError* retval = NULL;
-  if (ret.status.status)
-    retval = new RPCError(&ret.status);
-  else {
-    try {
-      try {
-        profile = ret.profile;
-        provider_id = ret.provider_id;
-        
-        // return the Authentication Statement
-        if (auth_statement) {
-          istringstream authstream(ret.auth_statement);
-          
-          log.debugStream() << "Trying to decode authentication statement: "
-                << ret.auth_statement << CategoryStream::ENDLINE;
-          *auth_statement = new SAMLAuthenticationStatement(authstream);
-        }
-
-        // return the unfiltered Response
-        if (attr_response_pre) {
-          istringstream prestream(ret.attr_response_pre);
-          
-          log.debugStream() << "Trying to decode unfiltered attribute response: "
-                << ret.attr_response_pre << CategoryStream::ENDLINE;
-          *attr_response_pre = new SAMLResponse(prestream);
-        }
-
-        // return the filtered Response
-        if (attr_response_post) {
-          istringstream poststream(ret.attr_response_post);
-          
-          log.debugStream() << "Trying to decode filtered attribute response: "
-                << ret.attr_response_post << CategoryStream::ENDLINE;
-          *attr_response_post = new SAMLResponse(poststream);
-        }
-      }
-      catch (SAMLException& e) {
-        log.error ("SAML Exception: %s", e.what());
-        ostringstream os;
-        os << e;
-        throw ShibTargetException(SHIBRPC_SAML_EXCEPTION, os.str().c_str());
-      }
-      catch (XMLException& e) {
-        log.error ("XML Exception: %s", e.getMessage());
-        auto_ptr_char msg(e.getMessage());
-        throw ShibTargetException (SHIBRPC_XML_EXCEPTION, msg.get());
-      }
-    }
-    catch (ShibTargetException &e) {
-      retval = new RPCError(e);
-    }
-
-    if (!retval)
-      retval = new RPCError();
-  }
+    return m_priv->m_conf;
+}
 
-  clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
-  rpc.pool();
+void* ShibTarget::returnDecline(void)
+{
+    return NULL;
+}
 
-  log.debug("returning");
-  return retval;
+void* ShibTarget::returnOK(void)
+{
+    return NULL;
 }
 
-/*************************************************************************
- * Shib Target Private implementation
- */
+static char x2c(char *what)
+{
+    register char digit;
 
-ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), session_id(NULL),
-    m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
+    digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
+    digit *= 16;
+    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
+    return(digit);
+}
 
-ShibTargetPriv::~ShibTargetPriv()
+void ShibTarget::url_decode(char* s)
 {
-  delete m_sso_statement;
-  m_sso_statement = NULL;
-
-  delete m_pre_response;
-  m_pre_response = NULL;
-  
-  delete m_post_response;
-  m_post_response = NULL;
+    register int x,y;
 
-  if (m_mapper) {
-    m_mapper->unlock();
-    m_mapper = NULL;
-  }
-  if (m_conf) {
-    m_conf->unlock();
-    m_conf = NULL;
-  }
-  m_app = NULL;
-  m_Config = NULL;
+    for(x=0,y=0;s[y];++x,++y)
+    {
+        if((s[x] = s[y]) == '%')
+        {
+            s[x] = x2c(&s[y+1]);
+            y+=2;
+        }
+    }
+    s[x] = '\0';
 }
 
 static inline char hexchar(unsigned short s)
@@ -1250,14 +852,13 @@ static inline char hexchar(unsigned short s)
     return (s<=9) ? ('0' + s) : ('A' + s - 10);
 }
 
-string
-ShibTargetPriv::url_encode(const char* s)
+string ShibTarget::url_encode(const char* s)
 {
     static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
 
     string ret;
     for (; *s; s++) {
-        if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
+        if (strchr(badchars,*s) || *s<=0x20 || *s>=0x7F) {
             ret+='%';
         ret+=hexchar(*s >> 4);
         ret+=hexchar(*s & 0x0F);
@@ -1268,8 +869,36 @@ ShibTargetPriv::url_encode(const char* s)
     return ret;
 }
 
-void
-ShibTargetPriv::get_application(const string& protocol, const string& hostname, int port, const string& uri)
+/*************************************************************************
+ * 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;
@@ -1286,121 +915,123 @@ ShibTargetPriv::get_application(const string& protocol, const string& hostname,
   m_mapper->lock();
 
   // Obtain the application settings from the parsed URL
-  m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
-                                                 hostname.c_str(),
-                                                 port, uri.c_str());
+  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");
-  const IApplication* application=m_conf->getApplication(application_id.second);
-  if (!application) {
+  m_app=m_conf->getApplication(application_id.second);
+  if (!m_app) {
     m_mapper->unlock();
     m_mapper = NULL;
     m_conf->unlock();
     m_conf = NULL;
-    throw ShibTargetException(SHIBRPC_OK, "unable to map request to application settings.  Check configuration");
+    throw ConfigurationException("Unable to map request to application settings, check configuration.");
   }
 
-  // Store the application for later use
-  m_app = application;
-
-  // Compute the target URL
-  m_url = protocol + "://" + hostname;
-  if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
-    m_url += ":" + port;
-  m_url += uri;
+  // 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, string page, ShibMLP &mlp)
+void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
 {
-  const IPropertySet* props=m_app->getPropertySet("Errors");
-  if (props) {
-    pair<bool,const char*> p=props->getString(page.c_str());
-    if (p.first) {
-      ifstream infile(p.second);
-      if (!infile.fail()) {
-       const char* res = mlp.run(infile,props);
-       if (res)
-         return st->sendPage(res);
-      }
+    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");
+    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));
+            }
+        }
+        else if (!strcmp(page,"access"))
+            return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
     }
-  }
 
-  string errstr = "sendError could not process the error template for application ";
-  errstr += m_app->getId();
-  st->log(ShibTarget::LogLevelError, errstr);
-  return st->sendPage("Internal Server Error.  Please contact the server administrator.");
+    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)
+        );
 }
 
-const char *
-ShibTargetPriv::getSessionId(ShibTarget* st)
+void ShibTargetPriv::clearHeaders(ShibTarget* st)
 {
-  if (session_id) {
-    //string m = string("getSessionId returning precreated session_id: ") + session_id;
-    //st->log(ShibTarget::LogLevelDebug, m);
-    return session_id;
-  }
+    // 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");
 
-  char *sid;
-  pair<const char*, const char *> shib_cookie = st->getCookieNameProps();
-  m_cookies = st->getCookies();
-  if (!m_cookies.empty()) {
-    if (sid = strstr(m_cookies.c_str(), shib_cookie.first)) {
-      // We found a cookie.  pull it out (our session_id)
-      sid += strlen(shib_cookie.first) + 1; // skip over the '='
-      char *cookieend = strchr(sid, ';');
-      if (cookieend)
-       *cookieend = '\0';
-      session_id = sid;
+    // 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);
+        }
     }
-  }
-
-  //string m = string("getSessionId returning new session_id: ") + session_id;
-  //st->log(ShibTarget::LogLevelDebug, m);
-  return session_id;
 }
 
 /*************************************************************************
  * CGI Parser implementation
  */
 
-CgiParse::CgiParse(const char* data, unsigned int len)
+CgiParse::CgiParse(const ShibTarget* st)
 {
-    const char* pch = data;
-    unsigned int cl = len;
+    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);
-        url_decode(value);
+        ShibTarget::url_decode(value);
         name=makeword(value,'=');
-        kvp_map[name]=value;
+        kvp_map.insert(pair<string,char*>(name,value));
         free(name);
     }
 }
 
 CgiParse::~CgiParse()
 {
-    for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
+    for (multimap<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
         free(i->second);
 }
 
-const char*
-CgiParse::get_value(const char* name) const
+pair<CgiParse::walker,CgiParse::walker> CgiParse::get_values(const char* name) const
 {
-    map<string,char*>::const_iterator i=kvp_map.find(name);
-    if (i==kvp_map.end())
-        return NULL;
-    return i->second;
+    return kvp_map.equal_range(name);
 }
 
 /* Parsing routines modified from NCSA source. */
-char *
-CgiParse::makeword(char *line, char stop)
+char* CgiParse::makeword(char *line, char stop)
 {
     int x = 0,y;
     char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
@@ -1419,8 +1050,7 @@ CgiParse::makeword(char *line, char stop)
     return word;
 }
 
-char *
-CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
+char* CgiParse::fmakeword(char stop, size_t *cl, const char** ppch)
 {
     int wsize;
     char *word;
@@ -1451,60 +1081,10 @@ CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
     }
 }
 
-void
-CgiParse::plustospace(char *str)
+void CgiParse::plustospace(char *str)
 {
     register int x;
 
     for(x=0;str[x];x++)
         if(str[x] == '+') str[x] = ' ';
 }
-
-char
-CgiParse::x2c(char *what)
-{
-    register char digit;
-
-    digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
-    digit *= 16;
-    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
-    return(digit);
-}
-
-void
-CgiParse::url_decode(char *url)
-{
-    register int x,y;
-
-    for(x=0,y=0;url[y];++x,++y)
-    {
-        if((url[x] = url[y]) == '%')
-        {
-            url[x] = x2c(&url[y+1]);
-            y+=2;
-        }
-    }
-    url[x] = '\0';
-}
-
-// Subclasses may not need to override these particular virtual methods.
-string ShibTarget::getAuthType(void)
-{
-  return string("shibboleth");
-}
-void* ShibTarget::returnDecline(void)
-{
-  return NULL;
-}
-void* ShibTarget::returnOK(void)
-{
-  return NULL;
-}
-HTAccessInfo* ShibTarget::getAccessInfo(void)
-{
-  return NULL;
-}
-HTGroupTable* ShibTarget::getGroupTable(string &user)
-{
-  return NULL;
-}