Path resolution for error templates.
[shibboleth/sp.git] / shibsp / ServiceProvider.cpp
index 3429361..df7cf81 100644 (file)
 #include "exceptions.h"
 #include "AccessControl.h"
 #include "Application.h"
-#include "Handler.h"
 #include "ServiceProvider.h"
 #include "SessionCache.h"
 #include "SPRequest.h"
+#include "attribute/Attribute.h"
+#include "handler/SessionInitiator.h"
 #include "util/TemplateParameters.h"
 
 #include <fstream>
 #include <sstream>
-#include <saml/saml2/metadata/Metadata.h>
-#include <saml/util/SAMLConstants.h>
 #include <xmltooling/XMLToolingConfig.h>
-#include <xmltooling/util/NDC.h>\r
-#include <xmltooling/util/XMLHelper.h>\r
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/PathResolver.h>
+#include <xmltooling/util/URLEncoder.h>
+#include <xmltooling/util/XMLHelper.h>
 
 using namespace shibsp;
-using namespace opensaml::saml2md;
-using namespace opensaml;
+using namespace xmltooling::logging;
 using namespace xmltooling;
 using namespace std;
 
 namespace shibsp {
-    //SHIBSP_DLLLOCAL PluginManager<ServiceProvider,const DOMElement*>::Factory XMLServiceProviderFactory;
+    SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
 
     long SHIBSP_DLLLOCAL sendError(
-        SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, const XMLToolingException* ex=NULL
+        Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
         )
     {
+        // The properties we need can be set in the RequestMap, or the Errors element.
+        bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=NULL;
+        pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,NULL);
+        pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
+        const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
+
+        try {
+            RequestMapper::Settings settings = request.getRequestSettings();
+            if (mderror)
+                pathname = settings.first->getString("metadataError");
+            if (!pathname.first) {
+                string pagename(page);
+                pagename += "Error";
+                pathname = settings.first->getString(pagename.c_str());
+            }
+            if (mayRedirect)
+                redirectErrors = settings.first->getString("redirectErrors");
+        }
+        catch (exception& ex) {
+            log.error(ex.what());
+        }
+
+        if (mayRedirect) {
+            // Check for redirection on errors instead of template.
+            if (!redirectErrors.first && props)
+                redirectErrors = props->getString("redirectErrors");
+            if (redirectErrors.first) {
+                string loc(redirectErrors.second);
+                loc = loc + '?' + tp.toQueryString();
+                return request.sendRedirect(loc.c_str());
+            }
+        }
+
         request.setContentType("text/html");
         request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
         request.setResponseHeader("Cache-Control","private,no-store,no-cache");
     
-        const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
-        if (props) {
-            pair<bool,const char*> p=props->getString(page);
-            if (p.first) {
-                ifstream infile(p.second);
-                if (infile) {
-                    tp.setPropertySet(props);
-                    stringstream str;
-                    XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, ex);
-                    return request.sendResponse(str);
-                }
-            }
-            else if (!strcmp(page,"access")) {
-                istringstream msg("Access Denied");
-                return static_cast<opensaml::GenericResponse&>(request).sendResponse(msg, HTTPResponse::SAML_HTTP_STATUS_FORBIDDEN);
+        if (!pathname.first && props) {
+            if (mderror)
+                pathname=props->getString("metadata");
+            if (!pathname.first)
+                pathname=props->getString(page);
+        }
+        if (pathname.first) {
+            string fname(pathname.second);
+            ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
+            if (infile) {
+                tp.setPropertySet(props);
+                stringstream str;
+                XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
+                return request.sendResponse(str);
             }
         }
+        
+        if (!strcmp(page,"access")) {
+            istringstream msg("Access Denied");
+            return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED);
+        }
     
-        string errstr = string("sendError could not process error template (") + page + ")";
-        request.log(SPRequest::SPError, errstr);
+        log.error("sendError could not process error template (%s)", page);
         istringstream msg("Internal Server Error. Please contact the site administrator.");
         return request.sendError(msg);
     }
     
     void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
-        // Clear invariant stuff.
-        request.clearHeader("Shib-Origin-Site");
-        request.clearHeader("Shib-Identity-Provider");
-        request.clearHeader("Shib-Authentication-Method");
-        request.clearHeader("Shib-NameIdentifier-Format");
-        request.clearHeader("Shib-Attributes");
-        request.clearHeader("Shib-Application-ID");
-    
-        // Clear out the list of mapped attributes
-        /* TODO: port
-        Iterator<IAAP*> provs=dynamic_cast<const IApplication&>(getApplication()).getAAPProviders();
-        while (provs.hasNext()) {
-            IAAP* aap=provs.next();
-            xmltooling::Locker locker(aap);
-            Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
-            while (rules.hasNext()) {
-                const char* header=rules.next()->getHeader();
-                if (header)
-                    request.clearHeader(header);
-            }
-        }
-        */
+        request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
+        request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
+        request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
+        request.clearHeader("Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
+        request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
+        request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
+        request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
+        request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
+        //request.clearHeader("Shib-Application-ID");   handle inside app method
+        request.getApplication().clearAttributeHeaders(request);
     }
-
-    static const XMLCh SessionInitiator[] =     UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);\r
 };
 
 void SHIBSP_API shibsp::registerServiceProviders()
 {
-    //SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
+    SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
 }
 
 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
 {
-#ifdef _DEBUG\r
-    xmltooling::NDC ndc("doAuthentication");\r
-#endif\r
-\r
-    const Application* app=NULL;\r
-    const char* procState = "Request Processing Error";\r
-    string targetURL = request.getRequestURL();\r
-\r
-    try {\r
-        RequestMapper::Settings settings = request.getRequestSettings();\r
-        app = &(request.getApplication());\r
-\r
-        // If not SSL, check to see if we should block or redirect it.\r
-        if (!request.isSecure()) {\r
-            pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");\r
-            if (redirectToSSL.first) {\r
-#ifdef HAVE_STRCASECMP\r
-                if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {\r
-#else\r
-                if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {\r
-#endif\r
-                    // Compute the new target URL\r
-                    string redirectURL = string("https://") + request.getHostname();\r
-                    if (strcmp(redirectToSSL.second,"443")) {\r
-                        redirectURL = redirectURL + ':' + redirectToSSL.second;\r
-                    }\r
-                    redirectURL += request.getRequestURI();\r
-                    return make_pair(true, request.sendRedirect(redirectURL.c_str()));\r
-                }\r
-                else {\r
-                    TemplateParameters tp;\r
-                    tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-                    return make_pair(true,sendError(request, app, "ssl", tp));\r
-                }\r
-            }\r
-        }\r
-        \r
-        const char* handlerURL=request.getHandlerURL(targetURL.c_str());\r
-        if (!handlerURL)\r
-            throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");\r
-\r
-        // If the request URL contains the handler base URL for this application, either dispatch\r
-        // directly (mainly Apache 2.0) or just pass back control.\r
-        if (strstr(targetURL.c_str(),handlerURL)) {\r
-            if (handler)\r
-                return doHandler(request);\r
-            else\r
-                return make_pair(true, request.returnOK());\r
-        }\r
-\r
-        // Three settings dictate how to proceed.\r
-        pair<bool,const char*> authType = settings.first->getString("authType");\r
-        pair<bool,bool> requireSession = settings.first->getBool("requireSession");\r
-        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");\r
-\r
-        // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,\r
-        // then we ignore this request and consider it unprotected. Apache might lie to us if\r
-        // ShibBasicHijack is on, but that's up to it.\r
-        if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&\r
-#ifdef HAVE_STRCASECMP\r
-                (!authType.first || strcasecmp(authType.second,"shibboleth")))\r
-#else\r
-                (!authType.first || _stricmp(authType.second,"shibboleth")))\r
-#endif\r
-            return make_pair(true,request.returnDecline());\r
-\r
-        // Fix for secadv 20050901\r
-        clearHeaders(request);\r
-\r
-        pair<string,const char*> shib_cookie = app->getCookieNameProps("_shibsession_");\r
-        const char* session_id = request.getCookie(shib_cookie.first.c_str());\r
-        if (!session_id || !*session_id) {\r
-            // No session.  Maybe that's acceptable?\r
-            if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)\r
-                return make_pair(true,request.returnOK());\r
-\r
-            // No cookie, but we require a session. Initiate a new session using the indicated method.\r
-            procState = "Session Initiator Error";\r
-            const Handler* initiator=NULL;\r
-            if (requireSessionWith.first) {\r
-                initiator=app->getSessionInitiatorById(requireSessionWith.second);\r
-                if (!initiator)\r
-                    throw ConfigurationException(\r
-                        "No session initiator found with id ($1), check requireSessionWith command.",\r
-                        params(1,requireSessionWith.second)\r
-                        );\r
-            }\r
-            else {\r
-                initiator=app->getDefaultSessionInitiator();\r
-                if (!initiator)\r
-                    throw ConfigurationException("No default session initiator found, check configuration.");\r
-            }\r
-\r
-            return initiator->run(request,false);\r
-        }\r
-\r
-        procState = "Session Processing Error";\r
-        const Session* session=NULL;\r
-        try {\r
-            session=request.getSession();\r
-            // Make a localized exception throw if the session isn't valid.\r
-            if (!session)\r
-                throw RetryableProfileException("Session no longer valid.");\r
-        }\r
-        catch (exception& e) {\r
-            request.log(SPRequest::SPWarn, string("session processing failed: ") + e.what());\r
-\r
-            // If no session is required, bail now.\r
-            if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)\r
-                // Has to be OK because DECLINED will just cause Apache\r
-                // to fail when it can't locate anything to process the\r
-                // AuthType.  No session plus requireSession false means\r
-                // do not authenticate the user at this time.\r
-                return make_pair(true, request.returnOK());\r
-\r
-            // Try and cast down.\r
-            exception* base = &e;\r
-            RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);\r
-            if (trycast) {\r
-                // Session is invalid but we can retry -- initiate a new session.\r
-                procState = "Session Initiator Error";\r
-                const Handler* initiator=NULL;\r
-                if (requireSessionWith.first) {\r
-                    initiator=app->getSessionInitiatorById(requireSessionWith.second);\r
-                    if (!initiator)\r
-                        throw ConfigurationException(\r
-                            "No session initiator found with id ($1), check requireSessionWith command.",\r
-                            params(1,requireSessionWith.second)\r
-                            );\r
-                }\r
-                else {\r
-                    initiator=app->getDefaultSessionInitiator();\r
-                    if (!initiator)\r
-                        throw ConfigurationException("No default session initiator found, check configuration.");\r
-                }\r
-                return initiator->run(request,false);\r
-            }\r
-            throw;    // send it to the outer handler\r
-        }\r
-\r
-        // We're done.  Everything is okay.  Nothing to report.  Nothing to do..\r
-        // Let the caller decide how to proceed.\r
-        request.log(SPRequest::SPDebug, "doAuthentication succeeded");\r
-        return make_pair(false,0);\r
-    }\r
-    catch (XMLToolingException& e) {\r
-        TemplateParameters tp;\r
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = e.what();\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "session", tp, &e));\r
-    }\r
-    catch (exception& e) {\r
-        TemplateParameters tp;\r
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = e.what();\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "session", tp));\r
-    }\r
-#ifndef _DEBUG\r
-    catch (...) {\r
-        TemplateParameters tp;\r
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = "Caught an unknown exception.";\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "session", tp));\r
-    }\r
-#endif\r
+#ifdef _DEBUG
+    xmltooling::NDC ndc("doAuthentication");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
+
+    const Application* app=NULL;
+    string targetURL = request.getRequestURL();
+
+    try {
+        RequestMapper::Settings settings = request.getRequestSettings();
+        app = &(request.getApplication());
+
+        // If not SSL, check to see if we should block or redirect it.
+        if (!request.isSecure()) {
+            pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
+            if (redirectToSSL.first) {
+#ifdef HAVE_STRCASECMP
+                if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
+#else
+                if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
+#endif
+                    // Compute the new target URL
+                    string redirectURL = string("https://") + request.getHostname();
+                    if (strcmp(redirectToSSL.second,"443")) {
+                        redirectURL = redirectURL + ':' + redirectToSSL.second;
+                    }
+                    redirectURL += request.getRequestURI();
+                    return make_pair(true, request.sendRedirect(redirectURL.c_str()));
+                }
+                else {
+                    TemplateParameters tp;
+                    tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+                    return make_pair(true,sendError(log, request, app, "ssl", tp, false));
+                }
+            }
+        }
+        
+        const char* handlerURL=request.getHandlerURL(targetURL.c_str());
+        if (!handlerURL)
+            throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
+
+        // If the request URL contains the handler base URL for this application, either dispatch
+        // directly (mainly Apache 2.0) or just pass back control.
+        if (strstr(targetURL.c_str(),handlerURL)) {
+            if (handler)
+                return doHandler(request);
+            else
+                return make_pair(true, request.returnOK());
+        }
+
+        // Three settings dictate how to proceed.
+        pair<bool,const char*> authType = settings.first->getString("authType");
+        pair<bool,bool> requireSession = settings.first->getBool("requireSession");
+        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
+
+        // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
+        // then we ignore this request and consider it unprotected. Apache might lie to us if
+        // 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 make_pair(true,request.returnDecline());
+
+        // Fix for secadv 20050901
+        clearHeaders(request);
+
+        Session* session = NULL;
+        try {
+            session = request.getSession();
+        }
+        catch (exception& e) {
+            log.warn("error during session lookup: %s", e.what());
+            // If it's not a retryable session failure, we throw to the outer handler for reporting.
+            if (dynamic_cast<opensaml::RetryableProfileException*>(&e)==NULL)
+                throw;
+        }
+
+        if (!session) {
+            // No session.  Maybe that's acceptable?
+            if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
+                return make_pair(true,request.returnOK());
+
+            // No session, but we require one. Initiate a new session using the indicated method.
+            const Handler* initiator=NULL;
+            if (requireSessionWith.first) {
+                initiator=app->getSessionInitiatorById(requireSessionWith.second);
+                if (!initiator) {
+                    throw ConfigurationException(
+                        "No session initiator found with id ($1), check requireSessionWith command.", params(1,requireSessionWith.second)
+                        );
+                }
+            }
+            else {
+                initiator=app->getDefaultSessionInitiator();
+                if (!initiator)
+                    throw ConfigurationException("No default session initiator found, check configuration.");
+            }
+
+            return initiator->run(request,false);
+        }
+
+        // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
+        // Let the caller decide how to proceed.
+        log.debug("doAuthentication succeeded");
+        return make_pair(false,0L);
+    }
+    catch (exception& e) {
+        TemplateParameters tp(&e);
+        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+        return make_pair(true,sendError(log, request, app, "session", tp));
+    }
 }
 
 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
 {
-#ifdef _DEBUG\r
-    xmltooling::NDC ndc("doAuthorization");\r
-#endif\r
-\r
-    const Application* app=NULL;\r
-    const char* procState = "Authorization Processing Error";\r
-    string targetURL = request.getRequestURL();\r
-\r
-    try {\r
-        RequestMapper::Settings settings = request.getRequestSettings();\r
-        app = &(request.getApplication());\r
-\r
-        // Three settings dictate how to proceed.\r
-        pair<bool,const char*> authType = settings.first->getString("authType");\r
-        pair<bool,bool> requireSession = settings.first->getBool("requireSession");\r
-        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");\r
-\r
-        // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,\r
-        // then we ignore this request and consider it unprotected. Apache might lie to us if\r
-        // ShibBasicHijack is on, but that's up to it.\r
-        if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&\r
-#ifdef HAVE_STRCASECMP\r
-                (!authType.first || strcasecmp(authType.second,"shibboleth")))\r
-#else\r
-                (!authType.first || _stricmp(authType.second,"shibboleth")))\r
-#endif\r
-            return make_pair(true,request.returnDecline());\r
-\r
-        // Do we have an access control plugin?\r
-        if (settings.second) {\r
-            const Session* session =NULL;\r
-               pair<string,const char*> shib_cookie=app->getCookieNameProps("_shibsession_");\r
-            const char *session_id = request.getCookie(shib_cookie.first.c_str());\r
-            try {\r
-                       if (session_id && *session_id) {\r
-                    session = request.getSession();\r
-                       }\r
-            }\r
-            catch (exception&) {\r
-                request.log(SPRequest::SPWarn, "unable to obtain session information to pass to access control provider");\r
-            }\r
-       \r
-            Locker acllock(settings.second);\r
-            if (settings.second->authorized(request,session)) {\r
-                // Let the caller decide how to proceed.\r
-                request.log(SPRequest::SPDebug, "access control provider granted access");\r
-                return make_pair(false,0);\r
-            }\r
-            else {\r
-                request.log(SPRequest::SPWarn, "access control provider denied access");\r
-                TemplateParameters tp;\r
-                tp.m_map["requestURL"] = targetURL;\r
-                return make_pair(true,sendError(request, app, "access", tp));\r
-            }\r
-            return make_pair(false,0);\r
-        }\r
-        else\r
-            return make_pair(true,request.returnDecline());\r
-    }\r
-    catch (XMLToolingException& e) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
+#ifdef _DEBUG
+    xmltooling::NDC ndc("doAuthorization");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
+
+    const Application* app=NULL;
+    string targetURL = request.getRequestURL();
+
+    try {
+        RequestMapper::Settings settings = request.getRequestSettings();
+        app = &(request.getApplication());
+
+        // Three settings dictate how to proceed.
+        pair<bool,const char*> authType = settings.first->getString("authType");
+        pair<bool,bool> requireSession = settings.first->getBool("requireSession");
+        pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
+
+        // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
+        // then we ignore this request and consider it unprotected. Apache might lie to us if
+        // 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 make_pair(true,request.returnDecline());
+
+        // Do we have an access control plugin?
+        if (settings.second) {
+            const Session* session = NULL;
+            try {
+                session = request.getSession(false);
+            }
+            catch (exception& e) {
+                log.warn("unable to obtain session to pass to access control provider: %s", e.what());
+            }
+       
+            Locker acllock(settings.second);
+            switch (settings.second->authorized(request,session)) {
+                case AccessControl::shib_acl_true:
+                    log.debug("access control provider granted access");
+                    return make_pair(true,request.returnOK());
+
+                case AccessControl::shib_acl_false:
+                {
+                    log.warn("access control provider denied access");
+                    TemplateParameters tp;
+                    tp.m_map["requestURL"] = targetURL;
+                    return make_pair(true,sendError(log, request, app, "access", tp, false));
+                }
+
+                default:
+                    // Use the "DECLINE" interface to signal we don't know what to do.
+                    return make_pair(true,request.returnDecline());
+            }
+        }
+        else {
+            return make_pair(true,request.returnDecline());
+        }
+    }
+    catch (exception& e) {
+        TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp, &e));
+        return make_pair(true,sendError(log, request, app, "access", tp));
     }
-    catch (exception& e) {\r
-        TemplateParameters tp;\r
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = e.what();\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "access", tp));\r
-    }\r
-#ifndef _DEBUG\r
-    catch (...) {\r
-        TemplateParameters tp;\r
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = "Caught an unknown exception.";\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "access", tp));\r
-    }\r
-#endif\r
 }
 
 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
 {
-#ifdef _DEBUG\r
-    xmltooling::NDC ndc("doExport");\r
-#endif\r
-\r
-    const Application* app=NULL;\r
-    const char* procState = "Attribute Processing Error";\r
-    string targetURL = request.getRequestURL();\r
-\r
-    try {\r
+#ifdef _DEBUG
+    xmltooling::NDC ndc("doExport");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
+
+    const Application* app=NULL;
+    string targetURL = request.getRequestURL();
+
+    try {
         RequestMapper::Settings settings = request.getRequestSettings();
         app = &(request.getApplication());
-\r
-        const Session* session=NULL;\r
-        pair<string,const char*> shib_cookie=app->getCookieNameProps("_shibsession_");\r
-        const char *session_id = request.getCookie(shib_cookie.first.c_str());\r
-        try {\r
-               if (session_id && *session_id) {\r
-                session = request.getSession();\r
-               }\r
-        }\r
-        catch (exception&) {\r
-            request.log(SPRequest::SPWarn, "unable to obtain session information to export into request headers");\r
-               // If we have to have a session, then this is a fatal error.\r
-               if (requireSession)\r
-                       throw;\r
-        }\r
-\r
-               // Still no data?\r
-        if (!session) {\r
-               if (requireSession)\r
-                       throw RetryableProfileException("Unable to obtain session information for request.");\r
-               else\r
-                       return make_pair(false,0);      // just bail silently\r
-        }\r
-        \r
-        /*\r
-        TODO: port to new cache API\r
-        // Extract data from session.\r
-        pair<const char*,const SAMLSubject*> sub=m_cacheEntry->getSubject(false,true);\r
-        pair<const char*,const SAMLResponse*> unfiltered=m_cacheEntry->getTokens(true,false);\r
-        pair<const char*,const SAMLResponse*> filtered=m_cacheEntry->getTokens(false,true);\r
-\r
-        // Maybe export the tokens.\r
-        pair<bool,bool> exp=m_settings.first->getBool("exportAssertion");\r
-        if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {\r
-            unsigned int outlen;\r
-            XMLByte* serialized =\r
-                Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);\r
-            XMLByte *pos, *pos2;\r
-            for (pos=serialized, pos2=serialized; *pos2; pos2++)\r
-                if (isgraph(*pos2))\r
-                    *pos++=*pos2;\r
-            *pos=0;\r
-            setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));\r
-            XMLString::release(&serialized);\r
-        }\r
-\r
-        // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.\r
-        setHeader("Shib-Origin-Site", m_cacheEntry->getProviderId());\r
-        setHeader("Shib-Identity-Provider", m_cacheEntry->getProviderId());\r
-        setHeader("Shib-Authentication-Method", m_cacheEntry->getAuthnContext());\r
-        \r
-        // Get the AAP providers, which contain the attribute policy info.\r
-        Iterator<IAAP*> provs=m_app->getAAPProviders();\r
-\r
-        // Export NameID?\r
-        while (provs.hasNext()) {\r
-            IAAP* aap=provs.next();\r
-            xmltooling::Locker locker(aap);\r
-            const XMLCh* format = sub.second->getNameIdentifier()->getFormat();\r
-            const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);\r
-            if (rule && rule->getHeader()) {\r
-                auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);\r
-                auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());\r
-                setHeader("Shib-NameIdentifier-Format", form.get());\r
-                if (!strcmp(rule->getHeader(),"REMOTE_USER"))\r
-                    setRemoteUser(nameid.get());\r
-                else\r
-                    setHeader(rule->getHeader(), nameid.get());\r
-            }\r
-        }\r
-        \r
-        setHeader("Shib-Application-ID", m_app->getId());\r
-    \r
-        // Export the attributes.\r
-        Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));\r
-        while (a_iter.hasNext()) {\r
-            SAMLAssertion* assert=a_iter.next();\r
-            Iterator<SAMLStatement*> statements=assert->getStatements();\r
-            while (statements.hasNext()) {\r
-                SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());\r
-                if (!astate)\r
-                    continue;\r
-                Iterator<SAMLAttribute*> attrs=astate->getAttributes();\r
-                while (attrs.hasNext()) {\r
-                    SAMLAttribute* attr=attrs.next();\r
-            \r
-                    // Are we supposed to export it?\r
-                    provs.reset();\r
-                    while (provs.hasNext()) {\r
-                        IAAP* aap=provs.next();\r
-                        xmltooling::Locker locker(aap);\r
-                        const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());\r
-                        if (!rule || !rule->getHeader())\r
-                            continue;\r
-                    \r
-                        Iterator<string> vals=attr->getSingleByteValues();\r
-                        if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())\r
-                            setRemoteUser(vals.next().c_str());\r
-                        else {\r
-                            int it=0;\r
-                            string header = getSecureHeader(rule->getHeader());\r
-                            if (!header.empty())\r
-                                it++;\r
-                            for (; vals.hasNext(); it++) {\r
-                                string value = vals.next();\r
-                                for (string::size_type pos = value.find_first_of(";", string::size_type(0));\r
-                                        pos != string::npos;\r
-                                        pos = value.find_first_of(";", pos)) {\r
-                                    value.insert(pos, "\\");\r
-                                    pos += 2;\r
-                                }\r
-                                if (it)\r
-                                    header += ";";\r
-                                header += value;\r
-                            }\r
-                            setHeader(rule->getHeader(), header.c_str());\r
-                        }\r
-                    }\r
-                }\r
-            }\r
-        }\r
-        */\r
-    \r
-        return make_pair(false,0);\r
-    }\r
-    catch (XMLToolingException& e) {\r
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = e.what();\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "rm", tp, &e));\r
-    }\r
+
+        const Session* session = NULL;
+        try {
+            session = request.getSession(false);
+        }
+        catch (exception& e) {
+            log.warn("unable to obtain session to export to request: %s", e.what());
+               // If we have to have a session, then this is a fatal error.
+               if (requireSession)
+                       throw;
+        }
+
+               // Still no data?
+        if (!session) {
+               if (requireSession)
+                throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
+               else
+                       return make_pair(false,0L);     // just bail silently
+        }
+        
+        request.setHeader("Shib-Application-ID", app->getId());
+        request.setHeader("Shib-Session-ID", session->getID());
+
+        // Export the IdP name and Authn method/context info.
+        const char* hval = session->getEntityID();
+        if (hval)
+            request.setHeader("Shib-Identity-Provider", hval);
+        hval = session->getAuthnInstant();
+        if (hval)
+            request.setHeader("Shib-Authentication-Instant", hval);
+        hval = session->getAuthnContextClassRef();
+        if (hval) {
+            request.setHeader("Shib-Authentication-Method", hval);
+            request.setHeader("Shib-AuthnContext-Class", hval);
+        }
+        hval = session->getAuthnContextDeclRef();
+        if (hval)
+            request.setHeader("Shib-AuthnContext-Decl", hval);
+        
+        // Maybe export the assertion keys.
+        pair<bool,bool> exp=settings.first->getBool("exportAssertion");
+        if (exp.first && exp.second) {
+            const PropertySet* sessions=app->getPropertySet("Sessions");
+            pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
+            if (!exportLocation.first)
+                log.warn("can't export assertions without an exportLocation Sessions property");
+            else {
+                const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
+                string exportName = "Shib-Assertion-00";
+                string baseURL;
+                if (!strncmp(exportLocation.second, "http", 4))
+                    baseURL = exportLocation.second;
+                else
+                    baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
+                baseURL = baseURL + "?key=" + session->getID() + "&ID=";
+                const vector<const char*>& tokens = session->getAssertionIDs();
+                vector<const char*>::size_type count = 0;
+                for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
+                    count++;
+                    *(exportName.rbegin()) = '0' + (count%10);
+                    *(++exportName.rbegin()) = '0' + (count/10);
+                    string fullURL = baseURL + encoder->encode(*tokenids);
+                    request.setHeader(exportName.c_str(), fullURL.c_str());
+                }
+                request.setHeader("Shib-Assertion-Count", exportName.c_str() + 15);
+            }
+        }
+
+        // Export the attributes.
+        const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
+        for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
+            string header(request.getSecureHeader(a->first.c_str()));
+            const vector<string>& vals = a->second->getSerializedValues();
+            for (vector<string>::const_iterator v = vals.begin(); v!=vals.end(); ++v) {
+                if (!header.empty())
+                    header += ";";
+                string::size_type pos = v->find_first_of(';',string::size_type(0));
+                if (pos!=string::npos) {
+                    string value(*v);
+                    for (; pos != string::npos; pos = value.find_first_of(';',pos)) {
+                        value.insert(pos, "\\");
+                        pos += 2;
+                    }
+                    header += value;
+                }
+                else {
+                    header += (*v);
+                }
+            }
+            request.setHeader(a->first.c_str(), header.c_str());
+        }
+
+        // Check for REMOTE_USER.
+        bool remoteUserSet = false;
+        const vector<string>& rmids = app->getRemoteUserAttributeIds();
+        for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
+            pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
+                attributes.equal_range(*rmid);
+            while (matches.first != matches.second) {
+                const vector<string>& vals = matches.first->second->getSerializedValues();
+                if (!vals.empty()) {
+                    request.setRemoteUser(vals.front().c_str());
+                    remoteUserSet = true;
+                    break;
+                }
+            }
+        }
+
+        return make_pair(false,0L);
+    }
     catch (exception& e) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
+        TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "rm", tp));
+        return make_pair(true,sendError(log, request, app, "session", tp));
     }
-#ifndef _DEBUG\r
-    catch (...) {\r
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;\r
-        tp.m_map["errorText"] = "Caught an unknown exception.";\r
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));\r
-        return make_pair(true,sendError(request, app, "rm", tp));\r
-    }\r
-#endif\r
 }
 
 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
@@ -538,15 +457,40 @@ pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
 #ifdef _DEBUG
     xmltooling::NDC ndc("doHandler");
 #endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
 
     const Application* app=NULL;
-    const char* procState = "Shibboleth Handler Error";
     string targetURL = request.getRequestURL();
 
     try {
         RequestMapper::Settings settings = request.getRequestSettings();
         app = &(request.getApplication());
 
+        // If not SSL, check to see if we should block or redirect it.
+        if (!request.isSecure()) {
+            pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
+            if (redirectToSSL.first) {
+#ifdef HAVE_STRCASECMP
+                if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
+#else
+                if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
+#endif
+                    // Compute the new target URL
+                    string redirectURL = string("https://") + request.getHostname();
+                    if (strcmp(redirectToSSL.second,"443")) {
+                        redirectURL = redirectURL + ':' + redirectToSSL.second;
+                    }
+                    redirectURL += request.getRequestURI();
+                    return make_pair(true, request.sendRedirect(redirectURL.c_str()));
+                }
+                else {
+                    TemplateParameters tp;
+                    tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
+                    return make_pair(true,sendError(log, request, app, "ssl", tp, false));
+                }
+            }
+        }
+
         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
         if (!handlerURL)
             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
@@ -563,67 +507,27 @@ pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
       
         // Make sure this is SSL, if it should be
-        if ((!handlerSSL.first || handlerSSL.second) && strcmp(request.getScheme(),"https"))
-            throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
+        if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
+            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 Handler* handler=app->getHandler(targetURL.c_str() + strlen(handlerURL));
         if (!handler)
-            throw BindingException("Shibboleth handler invoked at an unconfigured location.");
-
-        if (XMLHelper::isNodeNamed(handler->getElement(),samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME))
-            procState = "Session Creation Error";
-        else if (XMLString::equals(handler->getElement()->getLocalName(),SessionInitiator))
-            procState = "Session Initiator Error";
-        else if (XMLHelper::isNodeNamed(handler->getElement(),samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME))
-            procState = "Session Termination Error";
-        else
-            procState = "Protocol Handler Error";
+            throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
+
         pair<bool,long> hret=handler->run(request);
 
         // Did the handler run successfully?
         if (hret.first)
             return hret;
        
-        throw BindingException("Configured Shibboleth handler failed to process the request.");
-    }
-    catch (MetadataException& e) {
-        TemplateParameters tp;
-        tp.m_map["errorText"] = e.what();
-        // See if a metadata error page is installed.
-        const PropertySet* props=app->getPropertySet("Errors");
-        if (props) {
-            pair<bool,const char*> p=props->getString("metadata");
-            if (p.first) {
-                tp.m_map["errorType"] = procState;
-                tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-                return make_pair(true,sendError(request, app, "metadata", tp, &e));
-            }
-        }
-        throw;
-    }
-    catch (XMLToolingException& e) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp, &e));
+        throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
     }
     catch (exception& e) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = e.what();
+        TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
+        tp.m_request = &request;
+        return make_pair(true,sendError(log, request, app, "session", tp));
     }
-#ifndef _DEBUG
-    catch (...) {
-        TemplateParameters tp;
-        tp.m_map["errorType"] = procState;
-        tp.m_map["errorText"] = "Caught an unknown exception.";
-        tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "session", tp));
-    }
-#endif
 }