[shibboleth-sp2] 05/09: Re-convert linefeeds to undo Eclipse's handiwork

Ferenc Wágner wferi-guest at moszumanska.debian.org
Fri Mar 11 15:25:34 UTC 2016


This is an automated email from the git hooks/post-receive script.

wferi-guest pushed a commit to branch master
in repository shibboleth-sp2.

commit eab3df9a887298b7e35940a7a69c155832589457
Author: Scott Cantor <cantor.2 at osu.edu>
Date:   Thu Jan 28 16:05:44 2016 -0500

    Re-convert linefeeds to undo Eclipse's handiwork
---
 adfs/adfs.cpp           | 2156 +++++++++++-----------
 apache/mod_shib.cpp     | 4628 +++++++++++++++++++++++------------------------
 config_win32.h          |  326 ++--
 configs/shibboleth2.xml |  248 +--
 configure.ac            | 2762 ++++++++++++++--------------
 doc/README.txt          |   44 +-
 shibsp/version.h        |  160 +-
 7 files changed, 5162 insertions(+), 5162 deletions(-)

diff --git a/adfs/adfs.cpp b/adfs/adfs.cpp
index fccdd2c..c74912f 100644
--- a/adfs/adfs.cpp
+++ b/adfs/adfs.cpp
@@ -1,1078 +1,1078 @@
-/**
- * Licensed to the University Corporation for Advanced Internet
- * Development, Inc. (UCAID) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for
- * additional information regarding copyright ownership.
- *
- * UCAID licenses this file to you 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
- *
- * 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.
- */
-
-/**
- * adfs.cpp
- *
- * ADFSv1 extension library.
- */
-
-#if defined (_MSC_VER) || defined(__BORLANDC__)
-# include "config_win32.h"
-#else
-# include "config.h"
-#endif
-
-#ifdef WIN32
-# define _CRT_NONSTDC_NO_DEPRECATE 1
-# define _CRT_SECURE_NO_DEPRECATE 1
-# define ADFS_EXPORTS __declspec(dllexport)
-#else
-# define ADFS_EXPORTS
-#endif
-
-#include <shibsp/base.h>
-#include <shibsp/exceptions.h>
-#include <shibsp/Application.h>
-#include <shibsp/ServiceProvider.h>
-#include <shibsp/SessionCache.h>
-#include <shibsp/SPConfig.h>
-#include <shibsp/SPRequest.h>
-#include <shibsp/TransactionLog.h>
-#include <shibsp/handler/AssertionConsumerService.h>
-#include <shibsp/handler/LogoutInitiator.h>
-#include <shibsp/handler/SessionInitiator.h>
-#include <xmltooling/logging.h>
-#include <xmltooling/util/DateTime.h>
-#include <xmltooling/util/NDC.h>
-#include <xmltooling/util/URLEncoder.h>
-#include <xmltooling/util/XMLHelper.h>
-#include <memory>
-
-#ifndef SHIBSP_LITE
-# include <shibsp/attribute/resolver/ResolutionContext.h>
-# include <shibsp/metadata/MetadataProviderCriteria.h>
-# include <saml/SAMLConfig.h>
-# include <saml/exceptions.h>
-# include <saml/binding/SecurityPolicy.h>
-# include <saml/saml1/core/Assertions.h>
-# include <saml/saml2/core/Assertions.h>
-# include <saml/saml2/metadata/Metadata.h>
-# include <saml/saml2/metadata/EndpointManager.h>
-# include <xmltooling/XMLToolingConfig.h>
-# include <xmltooling/impl/AnyElement.h>
-# include <xmltooling/util/ParserPool.h>
-# include <xmltooling/validation/ValidatorSuite.h>
-using namespace opensaml::saml2md;
-# ifndef min
-#  define min(a,b)            (((a) < (b)) ? (a) : (b))
-# endif
-#endif
-using namespace shibsp;
-using namespace opensaml;
-using namespace xmltooling::logging;
-using namespace xmltooling;
-using namespace xercesc;
-using namespace boost;
-using namespace std;
-
-#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
-#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
-
-namespace {
-
-#ifndef SHIBSP_LITE
-    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
-    {
-        auto_ptr_XMLCh m_ns;
-    public:
-        ADFSDecoder() : m_ns(WSTRUST_NS) {}
-        virtual ~ADFSDecoder() {}
-
-        const XMLCh* getProtocolFamily() const {
-            return m_ns.get();
-        }
-
-        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
-
-    protected:
-        void extractMessageDetails(
-            const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
-            ) const {
-        }
-    };
-
-    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
-    {
-        return new ADFSDecoder();
-    }
-#endif
-
-#if defined (_MSC_VER)
-    #pragma warning( push )
-    #pragma warning( disable : 4250 )
-#endif
-
-    class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
-    {
-    public:
-        ADFSSessionInitiator(const DOMElement* e, const char* appId)
-            : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
-            // If Location isn't set, defer address registration until the setParent call.
-            pair<bool,const char*> loc = getString("Location");
-            if (loc.first) {
-                string address = m_appId + loc.second + "::run::ADFSSI";
-                setAddress(address.c_str());
-            }
-        }
-        virtual ~ADFSSessionInitiator() {}
-
-        void setParent(const PropertySet* parent) {
-            DOMPropertySet::setParent(parent);
-            pair<bool,const char*> loc = getString("Location");
-            if (loc.first) {
-                string address = m_appId + loc.second + "::run::ADFSSI";
-                setAddress(address.c_str());
-            }
-            else {
-                m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
-            }
-        }
-
-        void receive(DDF& in, ostream& out);
-        pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
-        pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
-
-        const XMLCh* getProtocolFamily() const {
-            return m_binding.get();
-        }
-
-#ifndef SHIBSP_LITE
-        void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
-            doGenerateMetadata(role, handlerURL);
-        }
-#endif
-
-    private:
-        pair<bool,long> doRequest(
-            const Application& application,
-            const HTTPRequest* httpRequest,
-            HTTPResponse& httpResponse,
-            const char* entityID,
-            const char* acsLocation,
-            const char* authnContextClassRef,
-            string& relayState
-            ) const;
-        string m_appId;
-        auto_ptr_XMLCh m_binding;
-    };
-
-    class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
-    {
-        auto_ptr_XMLCh m_protocol;
-    public:
-        ADFSConsumer(const DOMElement* e, const char* appId)
-            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT ".SSO.ADFS")), m_protocol(WSFED_NS) {}
-        virtual ~ADFSConsumer() {}
-
-#ifndef SHIBSP_LITE
-        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
-            AssertionConsumerService::generateMetadata(role, handlerURL);
-            role.addSupport(m_protocol.get());
-        }
-
-    private:
-        void implementProtocol(
-            const Application& application,
-            const HTTPRequest& httpRequest,
-            HTTPResponse& httpResponse,
-            SecurityPolicy& policy,
-            const PropertySet*,
-            const XMLObject& xmlObject
-            ) const;
-#else
-        const XMLCh* getProtocolFamily() const {
-            return m_protocol.get();
-        }
-#endif
-    };
-
-    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
-    {
-    public:
-        ADFSLogoutInitiator(const DOMElement* e, const char* appId)
-                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
-            // If Location isn't set, defer address registration until the setParent call.
-            pair<bool,const char*> loc = getString("Location");
-            if (loc.first) {
-                string address = m_appId + loc.second + "::run::ADFSLI";
-                setAddress(address.c_str());
-            }
-        }
-        virtual ~ADFSLogoutInitiator() {}
-
-        void setParent(const PropertySet* parent) {
-            DOMPropertySet::setParent(parent);
-            pair<bool,const char*> loc = getString("Location");
-            if (loc.first) {
-                string address = m_appId + loc.second + "::run::ADFSLI";
-                setAddress(address.c_str());
-            }
-            else {
-                m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
-            }
-        }
-
-        void receive(DDF& in, ostream& out);
-        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
-
-        const XMLCh* getProtocolFamily() const {
-            return m_binding.get();
-        }
-
-    private:
-        pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
-
-        string m_appId;
-        auto_ptr_XMLCh m_binding;
-    };
-
-    class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
-    {
-    public:
-        ADFSLogout(const DOMElement* e, const char* appId)
-                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".Logout.ADFS")), m_login(e, appId) {
-            m_initiator = false;
-#ifndef SHIBSP_LITE
-            m_preserve.push_back("wreply");
-            string address = string(appId) + getString("Location").second + "::run::ADFSLO";
-            setAddress(address.c_str());
-#endif
-        }
-        virtual ~ADFSLogout() {}
-
-        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
-
-#ifndef SHIBSP_LITE
-        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
-            m_login.generateMetadata(role, handlerURL);
-            const char* loc = getString("Location").second;
-            string hurl(handlerURL);
-            if (*loc != '/')
-                hurl += '/';
-            hurl += loc;
-            auto_ptr_XMLCh widen(hurl.c_str());
-            SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
-            ep->setLocation(widen.get());
-            ep->setBinding(m_login.getProtocolFamily());
-            role.getSingleLogoutServices().push_back(ep);
-        }
-
-        const char* getType() const {
-            return m_login.getType();
-        }
-#endif
-        const XMLCh* getProtocolFamily() const {
-            return m_login.getProtocolFamily();
-        }
-
-    private:
-        ADFSConsumer m_login;
-    };
-
-#if defined (_MSC_VER)
-    #pragma warning( pop )
-#endif
-
-    SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
-    {
-        return new ADFSSessionInitiator(p.first, p.second);
-    }
-
-    Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
-    {
-        return new ADFSLogout(p.first, p.second);
-    }
-
-    Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
-    {
-        return new ADFSLogoutInitiator(p.first, p.second);
-    }
-
-    const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);
-    const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);
-};
-
-extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
-{
-    SPConfig& conf=SPConfig::getConfig();
-    conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
-    conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
-    conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
-    conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
-#ifndef SHIBSP_LITE
-    SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
-    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
-    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
-#endif
-    return 0;
-}
-
-extern "C" void ADFS_EXPORTS xmltooling_extension_term()
-{
-    /* should get unregistered during normal shutdown...
-    SPConfig& conf=SPConfig::getConfig();
-    conf.SessionInitiatorManager.deregisterFactory("ADFS");
-    conf.LogoutInitiatorManager.deregisterFactory("ADFS");
-    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
-    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
-#ifndef SHIBSP_LITE
-    SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
-#endif
-    */
-}
-
-pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
-{
-    // We have to know the IdP to function.
-    if (entityID.empty() || !checkCompatibility(request, isHandler))
-        return make_pair(false, 0L);
-
-    string target;
-    pair<bool,const char*> prop;
-    pair<bool,const char*> acClass;
-    const Handler* ACS = nullptr;
-    const Application& app = request.getApplication();
-
-    if (isHandler) {
-        prop.second = request.getParameter("acsIndex");
-        if (prop.second && *prop.second) {
-            ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
-            if (!ACS)
-                request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
-        }
-
-        prop = getString("target", request);
-        if (prop.first)
-            target = prop.second;
-
-        // Since we're passing the ACS by value, we need to compute the return URL,
-        // so we'll need the target resource for real.
-        recoverRelayState(app, request, request, target, false);
-        app.limitRedirect(request, target.c_str());
-
-        acClass = getString("authnContextClassRef", request);
-    }
-    else {
-        // Check for a hardwired target value in the map or handler.
-        prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
-        if (prop.first)
-            target = prop.second;
-        else
-            target = request.getRequestURL();
-
-        acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
-    }
-
-    if (!ACS) {
-        pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
-        if (index.first)
-            ACS = app.getAssertionConsumerServiceByIndex(index.second);
-    }
-
-    // Validate the ACS for use with this protocol.
-    if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
-        if (ACS)
-            request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");
-        ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
-        if (!ACS)
-            throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
-    }
-
-    // Since we're not passing by index, we need to fully compute the return URL.
-    // Compute the ACS URL. We add the ACS location to the base handlerURL.
-    string ACSloc = request.getHandlerURL(target.c_str());
-    prop = ACS->getString("Location");
-    if (prop.first)
-        ACSloc += prop.second;
-
-    if (isHandler) {
-        // We may already have RelayState set if we looped back here,
-        // but we've turned it back into a resource by this point, so if there's
-        // a target on the URL, reset to that value.
-        prop.second = request.getParameter("target");
-        if (prop.second && *prop.second)
-            target = prop.second;
-    }
-
-    m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
-
-    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
-        // Out of process means the POST data via the request can be exposed directly to the private method.
-        // The method will handle POST preservation if necessary *before* issuing the response, but only if
-        // it dispatches to an IdP.
-        return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
-    }
-
-    // Remote the call.
-    DDF out,in = DDF(m_address.c_str()).structure();
-    DDFJanitor jin(in), jout(out);
-    in.addmember("application_id").string(app.getId());
-    in.addmember("entity_id").string(entityID.c_str());
-    in.addmember("acsLocation").string(ACSloc.c_str());
-    if (!target.empty())
-        in.addmember("RelayState").unsafe_string(target.c_str());
-    if (acClass.first)
-        in.addmember("authnContextClassRef").string(acClass.second);
-
-    // Remote the processing.
-    out = request.getServiceProvider().getListenerService()->send(in);
-    return unwrap(request, out);
-}
-
-pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
-{
-    // See if there's any response to send back.
-    if (!out["redirect"].isnull() || !out["response"].isnull()) {
-        // If so, we're responsible for handling the POST data, probably by dropping a cookie.
-        preservePostData(request.getApplication(), request, request, out["RelayState"].string());
-    }
-    return RemotedHandler::unwrap(request, out);
-}
-
-void ADFSSessionInitiator::receive(DDF& in, ostream& out)
-{
-    // Find application.
-    const char* aid = in["application_id"].string();
-    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
-    if (!app) {
-        // Something's horribly wrong.
-        m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
-        throw ConfigurationException("Unable to locate application for new session, deleted?");
-    }
-
-    const char* entityID = in["entity_id"].string();
-    const char* acsLocation = in["acsLocation"].string();
-    if (!entityID || !acsLocation)
-        throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
-
-    DDF ret(nullptr);
-    DDFJanitor jout(ret);
-
-    // Wrap the outgoing object with a Response facade.
-    scoped_ptr<HTTPResponse> http(getResponse(ret));
-
-    string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
-
-    // Since we're remoted, the result should either be a throw, which we pass on,
-    // a false/0 return, which we just return as an empty structure, or a response/redirect,
-    // which we capture in the facade and send back.
-    doRequest(*app, nullptr, *http, entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
-    if (!ret.isstruct())
-        ret.structure();
-    ret.addmember("RelayState").unsafe_string(relayState.c_str());
-    out << ret;
-}
-
-pair<bool,long> ADFSSessionInitiator::doRequest(
-    const Application& app,
-    const HTTPRequest* httpRequest,
-    HTTPResponse& httpResponse,
-    const char* entityID,
-    const char* acsLocation,
-    const char* authnContextClassRef,
-    string& relayState
-    ) const
-{
-#ifndef SHIBSP_LITE
-    // Use metadata to invoke the SSO service directly.
-    MetadataProvider* m = app.getMetadataProvider();
-    Locker locker(m);
-    MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
-    pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
-    if (!entity.first) {
-        m_log.warn("unable to locate metadata for provider (%s)", entityID);
-        throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
-    }
-    else if (!entity.second) {
-        m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
-        if (getParent())
-            return make_pair(false, 0L);
-        throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
-    }
-    const EndpointType* ep = EndpointManager<SingleSignOnService>(
-        dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
-        ).getByBinding(m_binding.get());
-    if (!ep) {
-        m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
-        if (getParent())
-            return make_pair(false, 0L);
-        throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
-    }
-
-    preserveRelayState(app, httpResponse, relayState);
-
-    scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
-    if (ar_event.get()) {
-        ar_event->m_binding = WSFED_NS;
-        ar_event->m_protocol = WSFED_NS;
-        ar_event->m_peer = entity.first;
-        app.getServiceProvider().getTransactionLog()->write(*ar_event);
-    }
-
-    // UTC timestamp
-    time_t epoch=time(nullptr);
-#ifndef HAVE_GMTIME_R
-    struct tm* ptime=gmtime(&epoch);
-#else
-    struct tm res;
-    struct tm* ptime=gmtime_r(&epoch,&res);
-#endif
-    char timebuf[32];
-    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
-
-    auto_ptr_char dest(ep->getLocation());
-    const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
-
-    string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
-        "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
-    if (authnContextClassRef)
-        req += "&wauth=" + urlenc->encode(authnContextClassRef);
-    if (!relayState.empty())
-        req += "&wctx=" + urlenc->encode(relayState.c_str());
-
-    if (httpRequest) {
-        // If the request object is available, we're responsible for the POST data.
-        preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
-    }
-
-    return make_pair(true, httpResponse.sendRedirect(req.c_str()));
-#else
-    return make_pair(false, 0L);
-#endif
-}
-
-#ifndef SHIBSP_LITE
-
-XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
-{
-#ifdef _DEBUG
-    xmltooling::NDC ndc("decode");
-#endif
-    Category& log = Category::getInstance(SHIBSP_LOGCAT ".MessageDecoder.ADFS");
-
-    log.debug("validating input");
-    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
-    if (!httpRequest)
-        throw BindingException("Unable to cast request object to HTTPRequest type.");
-    if (strcmp(httpRequest->getMethod(),"POST"))
-        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
-    const char* param = httpRequest->getParameter("wa");
-    if (!param || strcmp(param, "wsignin1.0"))
-        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
-    param = httpRequest->getParameter("wctx");
-    if (param)
-        relayState = param;
-
-    param = httpRequest->getParameter("wresult");
-    if (!param)
-        throw BindingException("Request missing wresult parameter.");
-
-    log.debug("decoded ADFS response:\n%s", param);
-
-    // Parse and bind the document into an XMLObject.
-    istringstream is(param);
-    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
-        : XMLToolingConfig::getConfig().getParser()).parse(is);
-    XercesJanitor<DOMDocument> janitor(doc);
-    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
-    janitor.release();
-
-    if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
-    	log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
-        throw BindingException("Decoded message was not of the appropriate type.");
-    }
-
-    SchemaValidators.validate(xmlObject.get());
-
-    // Skip policy step here, there's no security in the wrapper.
-    // policy.evaluate(*xmlObject.get(), &genericRequest);
-
-    return xmlObject.release();
-}
-
-void ADFSConsumer::implementProtocol(
-    const Application& application,
-    const HTTPRequest& httpRequest,
-    HTTPResponse& httpResponse,
-    SecurityPolicy& policy,
-    const PropertySet*,
-    const XMLObject& xmlObject
-    ) const
-{
-    // Implementation of ADFS profile.
-    m_log.debug("processing message against ADFS Passive Requester profile");
-
-    // With ADFS, all the security comes from the assertion, which is two levels down in the message.
-
-    const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
-    if (!response || !response->hasChildren())
-        throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
-
-    const Assertion* token = nullptr;
-    for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
-    	// Look for the RequestedSecurityToken element.
-    	if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
-    	    response = dynamic_cast<const ElementProxy*>(*xo);
-    	    if (!response || !response->hasChildren())
-    	        throw FatalProfileException("Token wrapper element did not contain a security token.");
-    	    token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
-    	    if (!token || !token->getSignature())
-    	        throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
-    	    break;
-    	}
-    }
-
-    // Extract message and issuer details from assertion.
-    extractMessageDetails(*token, m_protocol.get(), policy);
-
-    // Populate recipient as audience.
-    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
-    policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
-
-    // Run the policy over the assertion. Handles replay, freshness, and
-    // signature verification, assuming the relevant rules are configured,
-    // along with condition enforcement.
-    policy.evaluate(*token, &httpRequest);
-
-    // If no security is in place now, we kick it.
-    if (!policy.isAuthenticated())
-        throw SecurityPolicyException("Unable to establish security of incoming assertion.");
-
-    const saml1::NameIdentifier* saml1name=nullptr;
-    const saml1::AuthenticationStatement* saml1statement=nullptr;
-    const saml2::NameID* saml2name=nullptr;
-    const saml2::AuthnStatement* saml2statement=nullptr;
-    const XMLCh* authMethod=nullptr;
-    const XMLCh* authInstant=nullptr;
-    time_t now = time(nullptr), sessionExp = 0;
-    const PropertySet* sessionProps = application.getPropertySet("Sessions");
-
-    const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
-    if (saml1token) {
-        // Now do profile validation to ensure we can use it for SSO.
-        if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
-            throw FatalProfileException("Assertion did not contain time conditions.");
-        else if (saml1token->getAuthenticationStatements().empty())
-            throw FatalProfileException("Assertion did not contain an authentication statement.");
-
-        // authnskew allows rejection of SSO if AuthnInstant is too old.
-        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
-
-        saml1statement = saml1token->getAuthenticationStatements().front();
-        if (saml1statement->getAuthenticationInstant()) {
-            if (saml1statement->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
-                throw FatalProfileException("The login time at your identity provider was future-dated.");
-            }
-            else if (authnskew.first && authnskew.second && saml1statement->getAuthenticationInstantEpoch() <= now &&
-                    (now - saml1statement->getAuthenticationInstantEpoch() > authnskew.second)) {
-                throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the allowed limit.");
-            }
-        }
-        else if (authnskew.first && authnskew.second) {
-            throw FatalProfileException("Your identity provider did not supply a time of login, violating local policy.");
-        }
-
-        // Address checking.
-        saml1::SubjectLocality* locality = saml1statement->getSubjectLocality();
-        if (locality && locality->getIPAddress()) {
-            auto_ptr_char ip(locality->getIPAddress());
-            checkAddress(application, httpRequest, ip.get());
-        }
-
-        saml1name = saml1statement->getSubject()->getNameIdentifier();
-        authMethod = saml1statement->getAuthenticationMethod();
-        if (saml1statement->getAuthenticationInstant())
-            authInstant = saml1statement->getAuthenticationInstant()->getRawData();
-
-        // Session expiration.
-        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
-        if (!lifetime.first || lifetime.second == 0)
-            lifetime.second = 28800;
-        sessionExp = now + lifetime.second;
-    }
-    else {
-        const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
-        if (!saml2token)
-            throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
-
-        // Now do profile validation to ensure we can use it for SSO.
-        if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
-            throw FatalProfileException("Assertion did not contain time conditions.");
-        else if (saml2token->getAuthnStatements().empty())
-            throw FatalProfileException("Assertion did not contain an authentication statement.");
-
-        // authnskew allows rejection of SSO if AuthnInstant is too old.
-        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
-
-        saml2statement = saml2token->getAuthnStatements().front();
-        if (authnskew.first && authnskew.second &&
-                saml2statement->getAuthnInstant() && (now - saml2statement->getAuthnInstantEpoch() > authnskew.second))
-            throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
-
-        // Address checking.
-        saml2::SubjectLocality* locality = saml2statement->getSubjectLocality();
-        if (locality && locality->getAddress()) {
-            auto_ptr_char ip(locality->getAddress());
-            checkAddress(application, httpRequest, ip.get());
-        }
-
-        saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
-        if (saml2statement->getAuthnContext() && saml2statement->getAuthnContext()->getAuthnContextClassRef())
-            authMethod = saml2statement->getAuthnContext()->getAuthnContextClassRef()->getReference();
-        if (saml2statement->getAuthnInstant())
-            authInstant = saml2statement->getAuthnInstant()->getRawData();
-
-        // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
-        sessionExp = saml2statement->getSessionNotOnOrAfter() ? saml2statement->getSessionNotOnOrAfterEpoch() : 0;
-        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
-        if (!lifetime.first || lifetime.second == 0)
-            lifetime.second = 28800;
-        if (sessionExp == 0)
-            sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
-        else
-            sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
-    }
-
-    m_log.debug("ADFS profile processing completed successfully");
-
-    // We've successfully "accepted" the SSO token.
-    // To complete processing, we need to extract and resolve attributes and then create the session.
-
-    // Normalize a SAML 1.x NameIdentifier...
-    scoped_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
-    if (saml1name) {
-        nameid->setName(saml1name->getName());
-        nameid->setFormat(saml1name->getFormat());
-        nameid->setNameQualifier(saml1name->getNameQualifier());
-    }
-
-    // The context will handle deleting attributes and new tokens.
-    vector<const Assertion*> tokens(1,token);
-    scoped_ptr<ResolutionContext> ctx(
-        resolveAttributes(
-            application,
-            &httpRequest,
-            policy.getIssuerMetadata(),
-            m_protocol.get(),
-            nullptr,
-            saml1name,
-            saml1statement,
-            (saml1name ? nameid.get() : saml2name),
-            saml2statement,
-            authMethod,
-            nullptr,
-            &tokens
-            )
-        );
-
-    if (ctx.get()) {
-        // Copy over any new tokens, but leave them in the context for cleanup.
-        tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
-    }
-
-    string session_id;
-    application.getServiceProvider().getSessionCache()->insert(
-        session_id,
-        application,
-        httpRequest,
-        httpResponse,
-        sessionExp,
-        entity,
-        m_protocol.get(),
-        (saml1name ? nameid.get() : saml2name),
-        authInstant,
-        nullptr,
-        authMethod,
-        nullptr,
-        &tokens,
-        ctx ? &ctx->getResolvedAttributes() : nullptr
-        );
-
-    scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
-    if (login_event) {
-        login_event->m_sessionID = session_id.c_str();
-        login_event->m_peer = entity;
-        login_event->m_protocol = WSFED_NS;
-        login_event->m_binding = WSFED_NS;
-        login_event->m_saml1AuthnStatement = saml1statement;
-        login_event->m_nameID = (saml1name ? nameid.get() : saml2name);
-        login_event->m_saml2AuthnStatement = saml2statement;
-        if (ctx)
-            login_event->m_attributes = &ctx->getResolvedAttributes();
-        application.getServiceProvider().getTransactionLog()->write(*login_event);
-    }
-}
-
-#endif
-
-pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
-{
-    // Normally we'd do notifications and session clearage here, but ADFS logout
-    // is missing the needed request/response features, so we have to rely on
-    // the IdP half to notify us back about the logout and do the work there.
-    // Basically we have no way to tell in the Logout receiving handler whether
-    // we initiated the logout or not.
-
-    Session* session = nullptr;
-    try {
-        session = request.getSession(false, true, false);  // don't cache it and ignore all checks
-        if (!session)
-            return make_pair(false, 0L);
-
-        // We only handle ADFS sessions.
-        if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
-            session->unlock();
-            return make_pair(false, 0L);
-        }
-    }
-    catch (std::exception& ex) {
-        m_log.error("error accessing current session: %s", ex.what());
-        return make_pair(false,0L);
-    }
-
-    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
-        // When out of process, we run natively.
-        return doRequest(request.getApplication(), request, request, session);
-    }
-    else {
-        // When not out of process, we remote the request.
-        session->unlock();
-        vector<string> headers(1,"Cookie");
-        headers.push_back("User-Agent");
-        DDF out,in = wrap(request, &headers);
-        DDFJanitor jin(in), jout(out);
-        out=request.getServiceProvider().getListenerService()->send(in);
-        return unwrap(request, out);
-    }
-}
-
-void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
-{
-#ifndef SHIBSP_LITE
-    // Defer to base class for notifications
-    if (in["notify"].integer() == 1)
-        return LogoutHandler::receive(in, out);
-
-    // Find application.
-    const char* aid = in["application_id"].string();
-    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
-    if (!app) {
-        // Something's horribly wrong.
-        m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
-        throw ConfigurationException("Unable to locate application for logout, deleted?");
-    }
-
-    // Unpack the request.
-    scoped_ptr<HTTPRequest> req(getRequest(in));
-
-    // Set up a response shim.
-    DDF ret(nullptr);
-    DDFJanitor jout(ret);
-    scoped_ptr<HTTPResponse> resp(getResponse(ret));
-
-    Session* session = nullptr;
-    try {
-         session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
-    }
-    catch (std::exception& ex) {
-        m_log.error("error accessing current session: %s", ex.what());
-    }
-
-    // With no session, we just skip the request and let it fall through to an empty struct return.
-    if (session) {
-        if (session->getEntityID()) {
-            // Since we're remoted, the result should either be a throw, which we pass on,
-            // a false/0 return, which we just return as an empty structure, or a response/redirect,
-            // which we capture in the facade and send back.
-            doRequest(*app, *req, *resp, session);
-        }
-        else {
-            m_log.error("no issuing entityID found in session");
-            session->unlock();
-            app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
-        }
-    }
-    out << ret;
-#else
-    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
-#endif
-}
-
-pair<bool,long> ADFSLogoutInitiator::doRequest(
-    const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
-    ) const
-{
-    Locker sessionLocker(session, false);
-
-    // Do back channel notification.
-    vector<string> sessions(1, session->getID());
-    if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
-#ifndef SHIBSP_LITE
-        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
-        if (logout_event) {
-            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
-            application.getServiceProvider().getTransactionLog()->write(*logout_event);
-        }
-#endif
-        sessionLocker.assign();
-        session = nullptr;
-        application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
-        return sendLogoutPage(application, httpRequest, httpResponse, "partial");
-    }
-
-#ifndef SHIBSP_LITE
-    pair<bool,long> ret = make_pair(false, 0L);
-
-    try {
-        // With a session in hand, we can create a request message, if we can find a compatible endpoint.
-        MetadataProvider* m = application.getMetadataProvider();
-        Locker metadataLocker(m);
-        MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
-        pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
-        if (!entity.first) {
-            throw MetadataException(
-                "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
-                );
-        }
-        else if (!entity.second) {
-            throw MetadataException(
-                "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
-                );
-        }
-
-        const EndpointType* ep = EndpointManager<SingleLogoutService>(
-            dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
-            ).getByBinding(m_binding.get());
-        if (!ep) {
-            throw MetadataException(
-                "Unable to locate ADFS single logout service for identity provider ($entityID).",
-                namedparams(1, "entityID", session->getEntityID())
-                );
-        }
-
-        const char* returnloc = httpRequest.getParameter("return");
-        if (returnloc)
-            application.limitRedirect(httpRequest, returnloc);
-
-        // Log the request.
-        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
-        if (logout_event) {
-            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
-            application.getServiceProvider().getTransactionLog()->write(*logout_event);
-        }
-
-        auto_ptr_char dest(ep->getLocation());
-        string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
-        if (returnloc) {
-            req += "&wreply=";
-            if (*returnloc == '/') {
-                string s(returnloc);
-                httpRequest.absolutize(s);
-                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(s.c_str());
-            }
-            else {
-                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(returnloc);
-            }
-        }
-        ret.second = httpResponse.sendRedirect(req.c_str());
-        ret.first = true;
-
-        if (session) {
-            sessionLocker.assign();
-            session = nullptr;
-            application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
-        }
-    }
-    catch (MetadataException& mex) {
-        // Less noise for IdPs that don't support logout
-        m_log.info("unable to issue ADFS logout request: %s", mex.what());
-    }
-    catch (std::exception& ex) {
-        m_log.error("error issuing ADFS logout request: %s", ex.what());
-    }
-
-    return ret;
-#else
-    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
-#endif
-}
-
-pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
-{
-    // Defer to base class for front-channel loop first.
-    // This won't initiate the loop, only continue/end it.
-    pair<bool,long> ret = LogoutHandler::run(request, isHandler);
-    if (ret.first)
-        return ret;
-
-    // wa parameter indicates the "action" to perform
-    bool returning = false;
-    const char* param = request.getParameter("wa");
-    if (param) {
-        if (!strcmp(param, "wsignin1.0"))
-            return m_login.run(request, isHandler);
-        else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
-            throw FatalProfileException("Unsupported WS-Federation action parameter ($1).", params(1, param));
-    }
-    else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
-        throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
-    else
-        returning = true;
-
-    param = request.getParameter("wreply");
-    const Application& app = request.getApplication();
-
-    if (!returning) {
-        // Pass control to the first front channel notification point, if any.
-        map<string,string> parammap;
-        if (param)
-            parammap["wreply"] = param;
-        pair<bool,long> result = notifyFrontChannel(app, request, request, &parammap);
-        if (result.first)
-            return result;
-    }
-
-    // Best effort on back channel and to remove the user agent's session.
-    string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
-    if (!session_id.empty()) {
-        vector<string> sessions(1,session_id);
-        notifyBackChannel(app, request.getRequestURL(), sessions, false);
-        try {
-            app.getServiceProvider().getSessionCache()->remove(app, request, &request);
-        }
-        catch (std::exception& ex) {
-            m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
-        }
-    }
-
-    if (param) {
-        if (*param == '/') {
-            string p(param);
-            request.absolutize(p);
-            return make_pair(true, request.sendRedirect(p.c_str()));
-        }
-        else {
-            app.limitRedirect(request, param);
-            return make_pair(true, request.sendRedirect(param));
-        }
-    }
-    return sendLogoutPage(app, request, request, "global");
-}
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
+ *
+ * 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.
+ */
+
+/**
+ * adfs.cpp
+ *
+ * ADFSv1 extension library.
+ */
+
+#if defined (_MSC_VER) || defined(__BORLANDC__)
+# include "config_win32.h"
+#else
+# include "config.h"
+#endif
+
+#ifdef WIN32
+# define _CRT_NONSTDC_NO_DEPRECATE 1
+# define _CRT_SECURE_NO_DEPRECATE 1
+# define ADFS_EXPORTS __declspec(dllexport)
+#else
+# define ADFS_EXPORTS
+#endif
+
+#include <shibsp/base.h>
+#include <shibsp/exceptions.h>
+#include <shibsp/Application.h>
+#include <shibsp/ServiceProvider.h>
+#include <shibsp/SessionCache.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/SPRequest.h>
+#include <shibsp/TransactionLog.h>
+#include <shibsp/handler/AssertionConsumerService.h>
+#include <shibsp/handler/LogoutInitiator.h>
+#include <shibsp/handler/SessionInitiator.h>
+#include <xmltooling/logging.h>
+#include <xmltooling/util/DateTime.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/URLEncoder.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <memory>
+
+#ifndef SHIBSP_LITE
+# include <shibsp/attribute/resolver/ResolutionContext.h>
+# include <shibsp/metadata/MetadataProviderCriteria.h>
+# include <saml/SAMLConfig.h>
+# include <saml/exceptions.h>
+# include <saml/binding/SecurityPolicy.h>
+# include <saml/saml1/core/Assertions.h>
+# include <saml/saml2/core/Assertions.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/EndpointManager.h>
+# include <xmltooling/XMLToolingConfig.h>
+# include <xmltooling/impl/AnyElement.h>
+# include <xmltooling/util/ParserPool.h>
+# include <xmltooling/validation/ValidatorSuite.h>
+using namespace opensaml::saml2md;
+# ifndef min
+#  define min(a,b)            (((a) < (b)) ? (a) : (b))
+# endif
+#endif
+using namespace shibsp;
+using namespace opensaml;
+using namespace xmltooling::logging;
+using namespace xmltooling;
+using namespace xercesc;
+using namespace boost;
+using namespace std;
+
+#define WSFED_NS "http://schemas.xmlsoap.org/ws/2003/07/secext"
+#define WSTRUST_NS "http://schemas.xmlsoap.org/ws/2005/02/trust"
+
+namespace {
+
+#ifndef SHIBSP_LITE
+    class SHIBSP_DLLLOCAL ADFSDecoder : public MessageDecoder
+    {
+        auto_ptr_XMLCh m_ns;
+    public:
+        ADFSDecoder() : m_ns(WSTRUST_NS) {}
+        virtual ~ADFSDecoder() {}
+
+        const XMLCh* getProtocolFamily() const {
+            return m_ns.get();
+        }
+
+        XMLObject* decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const;
+
+    protected:
+        void extractMessageDetails(
+            const XMLObject& message, const GenericRequest& req, const XMLCh* protocol, SecurityPolicy& policy
+            ) const {
+        }
+    };
+
+    MessageDecoder* ADFSDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
+    {
+        return new ADFSDecoder();
+    }
+#endif
+
+#if defined (_MSC_VER)
+    #pragma warning( push )
+    #pragma warning( disable : 4250 )
+#endif
+
+    class SHIBSP_DLLLOCAL ADFSSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
+    {
+    public:
+        ADFSSessionInitiator(const DOMElement* e, const char* appId)
+            : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.ADFS"), nullptr, &m_remapper), m_appId(appId), m_binding(WSFED_NS) {
+            // If Location isn't set, defer address registration until the setParent call.
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSSI";
+                setAddress(address.c_str());
+            }
+        }
+        virtual ~ADFSSessionInitiator() {}
+
+        void setParent(const PropertySet* parent) {
+            DOMPropertySet::setParent(parent);
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSSI";
+                setAddress(address.c_str());
+            }
+            else {
+                m_log.warn("no Location property in ADFS SessionInitiator (or parent), can't register as remoted handler");
+            }
+        }
+
+        void receive(DDF& in, ostream& out);
+        pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
+        pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
+
+        const XMLCh* getProtocolFamily() const {
+            return m_binding.get();
+        }
+
+#ifndef SHIBSP_LITE
+        void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
+            doGenerateMetadata(role, handlerURL);
+        }
+#endif
+
+    private:
+        pair<bool,long> doRequest(
+            const Application& application,
+            const HTTPRequest* httpRequest,
+            HTTPResponse& httpResponse,
+            const char* entityID,
+            const char* acsLocation,
+            const char* authnContextClassRef,
+            string& relayState
+            ) const;
+        string m_appId;
+        auto_ptr_XMLCh m_binding;
+    };
+
+    class SHIBSP_DLLLOCAL ADFSConsumer : public shibsp::AssertionConsumerService
+    {
+        auto_ptr_XMLCh m_protocol;
+    public:
+        ADFSConsumer(const DOMElement* e, const char* appId)
+            : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT ".SSO.ADFS")), m_protocol(WSFED_NS) {}
+        virtual ~ADFSConsumer() {}
+
+#ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            AssertionConsumerService::generateMetadata(role, handlerURL);
+            role.addSupport(m_protocol.get());
+        }
+
+    private:
+        void implementProtocol(
+            const Application& application,
+            const HTTPRequest& httpRequest,
+            HTTPResponse& httpResponse,
+            SecurityPolicy& policy,
+            const PropertySet*,
+            const XMLObject& xmlObject
+            ) const;
+#else
+        const XMLCh* getProtocolFamily() const {
+            return m_protocol.get();
+        }
+#endif
+    };
+
+    class SHIBSP_DLLLOCAL ADFSLogoutInitiator : public AbstractHandler, public LogoutInitiator
+    {
+    public:
+        ADFSLogoutInitiator(const DOMElement* e, const char* appId)
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".LogoutInitiator.ADFS")), m_appId(appId), m_binding(WSFED_NS) {
+            // If Location isn't set, defer address registration until the setParent call.
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSLI";
+                setAddress(address.c_str());
+            }
+        }
+        virtual ~ADFSLogoutInitiator() {}
+
+        void setParent(const PropertySet* parent) {
+            DOMPropertySet::setParent(parent);
+            pair<bool,const char*> loc = getString("Location");
+            if (loc.first) {
+                string address = m_appId + loc.second + "::run::ADFSLI";
+                setAddress(address.c_str());
+            }
+            else {
+                m_log.warn("no Location property in ADFS LogoutInitiator (or parent), can't register as remoted handler");
+            }
+        }
+
+        void receive(DDF& in, ostream& out);
+        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
+
+        const XMLCh* getProtocolFamily() const {
+            return m_binding.get();
+        }
+
+    private:
+        pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session) const;
+
+        string m_appId;
+        auto_ptr_XMLCh m_binding;
+    };
+
+    class SHIBSP_DLLLOCAL ADFSLogout : public AbstractHandler, public LogoutHandler
+    {
+    public:
+        ADFSLogout(const DOMElement* e, const char* appId)
+                : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".Logout.ADFS")), m_login(e, appId) {
+            m_initiator = false;
+#ifndef SHIBSP_LITE
+            m_preserve.push_back("wreply");
+            string address = string(appId) + getString("Location").second + "::run::ADFSLO";
+            setAddress(address.c_str());
+#endif
+        }
+        virtual ~ADFSLogout() {}
+
+        pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
+
+#ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            m_login.generateMetadata(role, handlerURL);
+            const char* loc = getString("Location").second;
+            string hurl(handlerURL);
+            if (*loc != '/')
+                hurl += '/';
+            hurl += loc;
+            auto_ptr_XMLCh widen(hurl.c_str());
+            SingleLogoutService* ep = SingleLogoutServiceBuilder::buildSingleLogoutService();
+            ep->setLocation(widen.get());
+            ep->setBinding(m_login.getProtocolFamily());
+            role.getSingleLogoutServices().push_back(ep);
+        }
+
+        const char* getType() const {
+            return m_login.getType();
+        }
+#endif
+        const XMLCh* getProtocolFamily() const {
+            return m_login.getProtocolFamily();
+        }
+
+    private:
+        ADFSConsumer m_login;
+    };
+
+#if defined (_MSC_VER)
+    #pragma warning( pop )
+#endif
+
+    SessionInitiator* ADFSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSSessionInitiator(p.first, p.second);
+    }
+
+    Handler* ADFSLogoutFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSLogout(p.first, p.second);
+    }
+
+    Handler* ADFSLogoutInitiatorFactory(const pair<const DOMElement*,const char*>& p)
+    {
+        return new ADFSLogoutInitiator(p.first, p.second);
+    }
+
+    const XMLCh RequestedSecurityToken[] =      UNICODE_LITERAL_22(R,e,q,u,e,s,t,e,d,S,e,c,u,r,i,t,y,T,o,k,e,n);
+    const XMLCh RequestSecurityTokenResponse[] =UNICODE_LITERAL_28(R,e,q,u,e,s,t,S,e,c,u,r,i,t,y,T,o,k,e,n,R,e,s,p,o,n,s,e);
+};
+
+extern "C" int ADFS_EXPORTS xmltooling_extension_init(void*)
+{
+    SPConfig& conf=SPConfig::getConfig();
+    conf.SessionInitiatorManager.registerFactory("ADFS", ADFSSessionInitiatorFactory);
+    conf.LogoutInitiatorManager.registerFactory("ADFS", ADFSLogoutInitiatorFactory);
+    conf.AssertionConsumerServiceManager.registerFactory("ADFS", ADFSLogoutFactory);
+    conf.AssertionConsumerServiceManager.registerFactory(WSFED_NS, ADFSLogoutFactory);
+#ifndef SHIBSP_LITE
+    SAMLConfig::getConfig().MessageDecoderManager.registerFactory(WSFED_NS, ADFSDecoderFactory);
+    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestedSecurityToken"), new AnyElementBuilder());
+    XMLObjectBuilder::registerBuilder(xmltooling::QName(WSTRUST_NS,"RequestSecurityTokenResponse"), new AnyElementBuilder());
+#endif
+    return 0;
+}
+
+extern "C" void ADFS_EXPORTS xmltooling_extension_term()
+{
+    /* should get unregistered during normal shutdown...
+    SPConfig& conf=SPConfig::getConfig();
+    conf.SessionInitiatorManager.deregisterFactory("ADFS");
+    conf.LogoutInitiatorManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory("ADFS");
+    conf.AssertionConsumerServiceManager.deregisterFactory(WSFED_NS);
+#ifndef SHIBSP_LITE
+    SAMLConfig::getConfig().MessageDecoderManager.deregisterFactory(WSFED_NS);
+#endif
+    */
+}
+
+pair<bool,long> ADFSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
+{
+    // We have to know the IdP to function.
+    if (entityID.empty() || !checkCompatibility(request, isHandler))
+        return make_pair(false, 0L);
+
+    string target;
+    pair<bool,const char*> prop;
+    pair<bool,const char*> acClass;
+    const Handler* ACS = nullptr;
+    const Application& app = request.getApplication();
+
+    if (isHandler) {
+        prop.second = request.getParameter("acsIndex");
+        if (prop.second && *prop.second) {
+            ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
+            if (!ACS)
+                request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
+        }
+
+        prop = getString("target", request);
+        if (prop.first)
+            target = prop.second;
+
+        // Since we're passing the ACS by value, we need to compute the return URL,
+        // so we'll need the target resource for real.
+        recoverRelayState(app, request, request, target, false);
+        app.limitRedirect(request, target.c_str());
+
+        acClass = getString("authnContextClassRef", request);
+    }
+    else {
+        // Check for a hardwired target value in the map or handler.
+        prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
+        if (prop.first)
+            target = prop.second;
+        else
+            target = request.getRequestURL();
+
+        acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
+    }
+
+    if (!ACS) {
+        pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
+        if (index.first)
+            ACS = app.getAssertionConsumerServiceByIndex(index.second);
+    }
+
+    // Validate the ACS for use with this protocol.
+    if (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily())) {
+        if (ACS)
+            request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-ADFS ACS, using default ADFS ACS");
+        ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
+        if (!ACS)
+            throw ConfigurationException("Unable to locate an ADFS-compatible ACS in the configuration.");
+    }
+
+    // Since we're not passing by index, we need to fully compute the return URL.
+    // Compute the ACS URL. We add the ACS location to the base handlerURL.
+    string ACSloc = request.getHandlerURL(target.c_str());
+    prop = ACS->getString("Location");
+    if (prop.first)
+        ACSloc += prop.second;
+
+    if (isHandler) {
+        // We may already have RelayState set if we looped back here,
+        // but we've turned it back into a resource by this point, so if there's
+        // a target on the URL, reset to that value.
+        prop.second = request.getParameter("target");
+        if (prop.second && *prop.second)
+            target = prop.second;
+    }
+
+    m_log.debug("attempting to initiate session using ADFS with provider (%s)", entityID.c_str());
+
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+        // Out of process means the POST data via the request can be exposed directly to the private method.
+        // The method will handle POST preservation if necessary *before* issuing the response, but only if
+        // it dispatches to an IdP.
+        return doRequest(app, &request, request, entityID.c_str(), ACSloc.c_str(), (acClass.first ? acClass.second : nullptr), target);
+    }
+
+    // Remote the call.
+    DDF out,in = DDF(m_address.c_str()).structure();
+    DDFJanitor jin(in), jout(out);
+    in.addmember("application_id").string(app.getId());
+    in.addmember("entity_id").string(entityID.c_str());
+    in.addmember("acsLocation").string(ACSloc.c_str());
+    if (!target.empty())
+        in.addmember("RelayState").unsafe_string(target.c_str());
+    if (acClass.first)
+        in.addmember("authnContextClassRef").string(acClass.second);
+
+    // Remote the processing.
+    out = request.getServiceProvider().getListenerService()->send(in);
+    return unwrap(request, out);
+}
+
+pair<bool,long> ADFSSessionInitiator::unwrap(SPRequest& request, DDF& out) const
+{
+    // See if there's any response to send back.
+    if (!out["redirect"].isnull() || !out["response"].isnull()) {
+        // If so, we're responsible for handling the POST data, probably by dropping a cookie.
+        preservePostData(request.getApplication(), request, request, out["RelayState"].string());
+    }
+    return RemotedHandler::unwrap(request, out);
+}
+
+void ADFSSessionInitiator::receive(DDF& in, ostream& out)
+{
+    // Find application.
+    const char* aid = in["application_id"].string();
+    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
+    if (!app) {
+        // Something's horribly wrong.
+        m_log.error("couldn't find application (%s) to generate ADFS request", aid ? aid : "(missing)");
+        throw ConfigurationException("Unable to locate application for new session, deleted?");
+    }
+
+    const char* entityID = in["entity_id"].string();
+    const char* acsLocation = in["acsLocation"].string();
+    if (!entityID || !acsLocation)
+        throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
+
+    DDF ret(nullptr);
+    DDFJanitor jout(ret);
+
+    // Wrap the outgoing object with a Response facade.
+    scoped_ptr<HTTPResponse> http(getResponse(ret));
+
+    string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
+
+    // Since we're remoted, the result should either be a throw, which we pass on,
+    // a false/0 return, which we just return as an empty structure, or a response/redirect,
+    // which we capture in the facade and send back.
+    doRequest(*app, nullptr, *http, entityID, acsLocation, in["authnContextClassRef"].string(), relayState);
+    if (!ret.isstruct())
+        ret.structure();
+    ret.addmember("RelayState").unsafe_string(relayState.c_str());
+    out << ret;
+}
+
+pair<bool,long> ADFSSessionInitiator::doRequest(
+    const Application& app,
+    const HTTPRequest* httpRequest,
+    HTTPResponse& httpResponse,
+    const char* entityID,
+    const char* acsLocation,
+    const char* authnContextClassRef,
+    string& relayState
+    ) const
+{
+#ifndef SHIBSP_LITE
+    // Use metadata to invoke the SSO service directly.
+    MetadataProvider* m = app.getMetadataProvider();
+    Locker locker(m);
+    MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+    pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
+    if (!entity.first) {
+        m_log.warn("unable to locate metadata for provider (%s)", entityID);
+        throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+    else if (!entity.second) {
+        m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate ADFS-aware identity provider role for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false, 0L);
+        throw MetadataException("Unable to locate ADFS-aware identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+    const EndpointType* ep = EndpointManager<SingleSignOnService>(
+        dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleSignOnServices()
+        ).getByBinding(m_binding.get());
+    if (!ep) {
+        m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
+        if (getParent())
+            return make_pair(false, 0L);
+        throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
+    }
+
+    preserveRelayState(app, httpResponse, relayState);
+
+    scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
+    if (ar_event.get()) {
+        ar_event->m_binding = WSFED_NS;
+        ar_event->m_protocol = WSFED_NS;
+        ar_event->m_peer = entity.first;
+        app.getServiceProvider().getTransactionLog()->write(*ar_event);
+    }
+
+    // UTC timestamp
+    time_t epoch=time(nullptr);
+#ifndef HAVE_GMTIME_R
+    struct tm* ptime=gmtime(&epoch);
+#else
+    struct tm res;
+    struct tm* ptime=gmtime_r(&epoch,&res);
+#endif
+    char timebuf[32];
+    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
+
+    auto_ptr_char dest(ep->getLocation());
+    const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
+
+    string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignin1.0&wreply=" + urlenc->encode(acsLocation) +
+        "&wct=" + urlenc->encode(timebuf) + "&wtrealm=" + urlenc->encode(app.getString("entityID").second);
+    if (authnContextClassRef)
+        req += "&wauth=" + urlenc->encode(authnContextClassRef);
+    if (!relayState.empty())
+        req += "&wctx=" + urlenc->encode(relayState.c_str());
+
+    if (httpRequest) {
+        // If the request object is available, we're responsible for the POST data.
+        preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
+    }
+
+    return make_pair(true, httpResponse.sendRedirect(req.c_str()));
+#else
+    return make_pair(false, 0L);
+#endif
+}
+
+#ifndef SHIBSP_LITE
+
+XMLObject* ADFSDecoder::decode(string& relayState, const GenericRequest& genericRequest, SecurityPolicy& policy) const
+{
+#ifdef _DEBUG
+    xmltooling::NDC ndc("decode");
+#endif
+    Category& log = Category::getInstance(SHIBSP_LOGCAT ".MessageDecoder.ADFS");
+
+    log.debug("validating input");
+    const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
+    if (!httpRequest)
+        throw BindingException("Unable to cast request object to HTTPRequest type.");
+    if (strcmp(httpRequest->getMethod(),"POST"))
+        throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
+    const char* param = httpRequest->getParameter("wa");
+    if (!param || strcmp(param, "wsignin1.0"))
+        throw BindingException("Missing or invalid wa parameter (should be wsignin1.0).");
+    param = httpRequest->getParameter("wctx");
+    if (param)
+        relayState = param;
+
+    param = httpRequest->getParameter("wresult");
+    if (!param)
+        throw BindingException("Request missing wresult parameter.");
+
+    log.debug("decoded ADFS response:\n%s", param);
+
+    // Parse and bind the document into an XMLObject.
+    istringstream is(param);
+    DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
+        : XMLToolingConfig::getConfig().getParser()).parse(is);
+    XercesJanitor<DOMDocument> janitor(doc);
+    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
+    janitor.release();
+
+    if (!XMLString::equals(xmlObject->getElementQName().getLocalPart(), RequestSecurityTokenResponse)) {
+    	log.error("unrecognized root element on message: %s", xmlObject->getElementQName().toString().c_str());
+        throw BindingException("Decoded message was not of the appropriate type.");
+    }
+
+    SchemaValidators.validate(xmlObject.get());
+
+    // Skip policy step here, there's no security in the wrapper.
+    // policy.evaluate(*xmlObject.get(), &genericRequest);
+
+    return xmlObject.release();
+}
+
+void ADFSConsumer::implementProtocol(
+    const Application& application,
+    const HTTPRequest& httpRequest,
+    HTTPResponse& httpResponse,
+    SecurityPolicy& policy,
+    const PropertySet*,
+    const XMLObject& xmlObject
+    ) const
+{
+    // Implementation of ADFS profile.
+    m_log.debug("processing message against ADFS Passive Requester profile");
+
+    // With ADFS, all the security comes from the assertion, which is two levels down in the message.
+
+    const ElementProxy* response = dynamic_cast<const ElementProxy*>(&xmlObject);
+    if (!response || !response->hasChildren())
+        throw FatalProfileException("Incoming message was not of the proper type or contains no security token.");
+
+    const Assertion* token = nullptr;
+    for (vector<XMLObject*>::const_iterator xo = response->getUnknownXMLObjects().begin(); xo != response->getUnknownXMLObjects().end(); ++xo) {
+    	// Look for the RequestedSecurityToken element.
+    	if (XMLString::equals((*xo)->getElementQName().getLocalPart(), RequestedSecurityToken)) {
+    	    response = dynamic_cast<const ElementProxy*>(*xo);
+    	    if (!response || !response->hasChildren())
+    	        throw FatalProfileException("Token wrapper element did not contain a security token.");
+    	    token = dynamic_cast<const Assertion*>(response->getUnknownXMLObjects().front());
+    	    if (!token || !token->getSignature())
+    	        throw FatalProfileException("Incoming message did not contain a signed SAML assertion.");
+    	    break;
+    	}
+    }
+
+    // Extract message and issuer details from assertion.
+    extractMessageDetails(*token, m_protocol.get(), policy);
+
+    // Populate recipient as audience.
+    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
+    policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
+
+    // Run the policy over the assertion. Handles replay, freshness, and
+    // signature verification, assuming the relevant rules are configured,
+    // along with condition enforcement.
+    policy.evaluate(*token, &httpRequest);
+
+    // If no security is in place now, we kick it.
+    if (!policy.isAuthenticated())
+        throw SecurityPolicyException("Unable to establish security of incoming assertion.");
+
+    const saml1::NameIdentifier* saml1name=nullptr;
+    const saml1::AuthenticationStatement* saml1statement=nullptr;
+    const saml2::NameID* saml2name=nullptr;
+    const saml2::AuthnStatement* saml2statement=nullptr;
+    const XMLCh* authMethod=nullptr;
+    const XMLCh* authInstant=nullptr;
+    time_t now = time(nullptr), sessionExp = 0;
+    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+
+    const saml1::Assertion* saml1token = dynamic_cast<const saml1::Assertion*>(token);
+    if (saml1token) {
+        // Now do profile validation to ensure we can use it for SSO.
+        if (!saml1token->getConditions() || !saml1token->getConditions()->getNotBefore() || !saml1token->getConditions()->getNotOnOrAfter())
+            throw FatalProfileException("Assertion did not contain time conditions.");
+        else if (saml1token->getAuthenticationStatements().empty())
+            throw FatalProfileException("Assertion did not contain an authentication statement.");
+
+        // authnskew allows rejection of SSO if AuthnInstant is too old.
+        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
+
+        saml1statement = saml1token->getAuthenticationStatements().front();
+        if (saml1statement->getAuthenticationInstant()) {
+            if (saml1statement->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
+                throw FatalProfileException("The login time at your identity provider was future-dated.");
+            }
+            else if (authnskew.first && authnskew.second && saml1statement->getAuthenticationInstantEpoch() <= now &&
+                    (now - saml1statement->getAuthenticationInstantEpoch() > authnskew.second)) {
+                throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the allowed limit.");
+            }
+        }
+        else if (authnskew.first && authnskew.second) {
+            throw FatalProfileException("Your identity provider did not supply a time of login, violating local policy.");
+        }
+
+        // Address checking.
+        saml1::SubjectLocality* locality = saml1statement->getSubjectLocality();
+        if (locality && locality->getIPAddress()) {
+            auto_ptr_char ip(locality->getIPAddress());
+            checkAddress(application, httpRequest, ip.get());
+        }
+
+        saml1name = saml1statement->getSubject()->getNameIdentifier();
+        authMethod = saml1statement->getAuthenticationMethod();
+        if (saml1statement->getAuthenticationInstant())
+            authInstant = saml1statement->getAuthenticationInstant()->getRawData();
+
+        // Session expiration.
+        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
+        if (!lifetime.first || lifetime.second == 0)
+            lifetime.second = 28800;
+        sessionExp = now + lifetime.second;
+    }
+    else {
+        const saml2::Assertion* saml2token = dynamic_cast<const saml2::Assertion*>(token);
+        if (!saml2token)
+            throw FatalProfileException("Incoming message did not contain a recognized type of SAML assertion.");
+
+        // Now do profile validation to ensure we can use it for SSO.
+        if (!saml2token->getConditions() || !saml2token->getConditions()->getNotBefore() || !saml2token->getConditions()->getNotOnOrAfter())
+            throw FatalProfileException("Assertion did not contain time conditions.");
+        else if (saml2token->getAuthnStatements().empty())
+            throw FatalProfileException("Assertion did not contain an authentication statement.");
+
+        // authnskew allows rejection of SSO if AuthnInstant is too old.
+        pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
+
+        saml2statement = saml2token->getAuthnStatements().front();
+        if (authnskew.first && authnskew.second &&
+                saml2statement->getAuthnInstant() && (now - saml2statement->getAuthnInstantEpoch() > authnskew.second))
+            throw FatalProfileException("The gap between now and the time you logged into your identity provider exceeds the limit.");
+
+        // Address checking.
+        saml2::SubjectLocality* locality = saml2statement->getSubjectLocality();
+        if (locality && locality->getAddress()) {
+            auto_ptr_char ip(locality->getAddress());
+            checkAddress(application, httpRequest, ip.get());
+        }
+
+        saml2name = saml2token->getSubject() ? saml2token->getSubject()->getNameID() : nullptr;
+        if (saml2statement->getAuthnContext() && saml2statement->getAuthnContext()->getAuthnContextClassRef())
+            authMethod = saml2statement->getAuthnContext()->getAuthnContextClassRef()->getReference();
+        if (saml2statement->getAuthnInstant())
+            authInstant = saml2statement->getAuthnInstant()->getRawData();
+
+        // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
+        sessionExp = saml2statement->getSessionNotOnOrAfter() ? saml2statement->getSessionNotOnOrAfterEpoch() : 0;
+        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
+        if (!lifetime.first || lifetime.second == 0)
+            lifetime.second = 28800;
+        if (sessionExp == 0)
+            sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
+        else
+            sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
+    }
+
+    m_log.debug("ADFS profile processing completed successfully");
+
+    // We've successfully "accepted" the SSO token.
+    // To complete processing, we need to extract and resolve attributes and then create the session.
+
+    // Normalize a SAML 1.x NameIdentifier...
+    scoped_ptr<saml2::NameID> nameid(saml1name ? saml2::NameIDBuilder::buildNameID() : nullptr);
+    if (saml1name) {
+        nameid->setName(saml1name->getName());
+        nameid->setFormat(saml1name->getFormat());
+        nameid->setNameQualifier(saml1name->getNameQualifier());
+    }
+
+    // The context will handle deleting attributes and new tokens.
+    vector<const Assertion*> tokens(1,token);
+    scoped_ptr<ResolutionContext> ctx(
+        resolveAttributes(
+            application,
+            &httpRequest,
+            policy.getIssuerMetadata(),
+            m_protocol.get(),
+            nullptr,
+            saml1name,
+            saml1statement,
+            (saml1name ? nameid.get() : saml2name),
+            saml2statement,
+            authMethod,
+            nullptr,
+            &tokens
+            )
+        );
+
+    if (ctx.get()) {
+        // Copy over any new tokens, but leave them in the context for cleanup.
+        tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
+    }
+
+    string session_id;
+    application.getServiceProvider().getSessionCache()->insert(
+        session_id,
+        application,
+        httpRequest,
+        httpResponse,
+        sessionExp,
+        entity,
+        m_protocol.get(),
+        (saml1name ? nameid.get() : saml2name),
+        authInstant,
+        nullptr,
+        authMethod,
+        nullptr,
+        &tokens,
+        ctx ? &ctx->getResolvedAttributes() : nullptr
+        );
+
+    scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
+    if (login_event) {
+        login_event->m_sessionID = session_id.c_str();
+        login_event->m_peer = entity;
+        login_event->m_protocol = WSFED_NS;
+        login_event->m_binding = WSFED_NS;
+        login_event->m_saml1AuthnStatement = saml1statement;
+        login_event->m_nameID = (saml1name ? nameid.get() : saml2name);
+        login_event->m_saml2AuthnStatement = saml2statement;
+        if (ctx)
+            login_event->m_attributes = &ctx->getResolvedAttributes();
+        application.getServiceProvider().getTransactionLog()->write(*login_event);
+    }
+}
+
+#endif
+
+pair<bool,long> ADFSLogoutInitiator::run(SPRequest& request, bool isHandler) const
+{
+    // Normally we'd do notifications and session clearage here, but ADFS logout
+    // is missing the needed request/response features, so we have to rely on
+    // the IdP half to notify us back about the logout and do the work there.
+    // Basically we have no way to tell in the Logout receiving handler whether
+    // we initiated the logout or not.
+
+    Session* session = nullptr;
+    try {
+        session = request.getSession(false, true, false);  // don't cache it and ignore all checks
+        if (!session)
+            return make_pair(false, 0L);
+
+        // We only handle ADFS sessions.
+        if (!XMLString::equals(session->getProtocol(), WSFED_NS) || !session->getEntityID()) {
+            session->unlock();
+            return make_pair(false, 0L);
+        }
+    }
+    catch (std::exception& ex) {
+        m_log.error("error accessing current session: %s", ex.what());
+        return make_pair(false,0L);
+    }
+
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+        // When out of process, we run natively.
+        return doRequest(request.getApplication(), request, request, session);
+    }
+    else {
+        // When not out of process, we remote the request.
+        session->unlock();
+        vector<string> headers(1,"Cookie");
+        headers.push_back("User-Agent");
+        DDF out,in = wrap(request, &headers);
+        DDFJanitor jin(in), jout(out);
+        out=request.getServiceProvider().getListenerService()->send(in);
+        return unwrap(request, out);
+    }
+}
+
+void ADFSLogoutInitiator::receive(DDF& in, ostream& out)
+{
+#ifndef SHIBSP_LITE
+    // Defer to base class for notifications
+    if (in["notify"].integer() == 1)
+        return LogoutHandler::receive(in, out);
+
+    // Find application.
+    const char* aid = in["application_id"].string();
+    const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
+    if (!app) {
+        // Something's horribly wrong.
+        m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
+        throw ConfigurationException("Unable to locate application for logout, deleted?");
+    }
+
+    // Unpack the request.
+    scoped_ptr<HTTPRequest> req(getRequest(in));
+
+    // Set up a response shim.
+    DDF ret(nullptr);
+    DDFJanitor jout(ret);
+    scoped_ptr<HTTPResponse> resp(getResponse(ret));
+
+    Session* session = nullptr;
+    try {
+         session = app->getServiceProvider().getSessionCache()->find(*app, *req, nullptr, nullptr);
+    }
+    catch (std::exception& ex) {
+        m_log.error("error accessing current session: %s", ex.what());
+    }
+
+    // With no session, we just skip the request and let it fall through to an empty struct return.
+    if (session) {
+        if (session->getEntityID()) {
+            // Since we're remoted, the result should either be a throw, which we pass on,
+            // a false/0 return, which we just return as an empty structure, or a response/redirect,
+            // which we capture in the facade and send back.
+            doRequest(*app, *req, *resp, session);
+        }
+        else {
+            m_log.error("no issuing entityID found in session");
+            session->unlock();
+            app->getServiceProvider().getSessionCache()->remove(*app, *req, resp.get());
+        }
+    }
+    out << ret;
+#else
+    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
+#endif
+}
+
+pair<bool,long> ADFSLogoutInitiator::doRequest(
+    const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, Session* session
+    ) const
+{
+    Locker sessionLocker(session, false);
+
+    // Do back channel notification.
+    vector<string> sessions(1, session->getID());
+    if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
+#ifndef SHIBSP_LITE
+        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
+        if (logout_event) {
+            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_PARTIAL;
+            application.getServiceProvider().getTransactionLog()->write(*logout_event);
+        }
+#endif
+        sessionLocker.assign();
+        session = nullptr;
+        application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
+        return sendLogoutPage(application, httpRequest, httpResponse, "partial");
+    }
+
+#ifndef SHIBSP_LITE
+    pair<bool,long> ret = make_pair(false, 0L);
+
+    try {
+        // With a session in hand, we can create a request message, if we can find a compatible endpoint.
+        MetadataProvider* m = application.getMetadataProvider();
+        Locker metadataLocker(m);
+        MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, m_binding.get());
+        pair<const EntityDescriptor*,const RoleDescriptor*> entity=m->getEntityDescriptor(mc);
+        if (!entity.first) {
+            throw MetadataException(
+                "Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", session->getEntityID())
+                );
+        }
+        else if (!entity.second) {
+            throw MetadataException(
+                "Unable to locate ADFS IdP role for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
+                );
+        }
+
+        const EndpointType* ep = EndpointManager<SingleLogoutService>(
+            dynamic_cast<const IDPSSODescriptor*>(entity.second)->getSingleLogoutServices()
+            ).getByBinding(m_binding.get());
+        if (!ep) {
+            throw MetadataException(
+                "Unable to locate ADFS single logout service for identity provider ($entityID).",
+                namedparams(1, "entityID", session->getEntityID())
+                );
+        }
+
+        const char* returnloc = httpRequest.getParameter("return");
+        if (returnloc)
+            application.limitRedirect(httpRequest, returnloc);
+
+        // Log the request.
+        scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(application, &httpRequest, session));
+        if (logout_event) {
+            logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_UNKNOWN;
+            application.getServiceProvider().getTransactionLog()->write(*logout_event);
+        }
+
+        auto_ptr_char dest(ep->getLocation());
+        string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "wa=wsignout1.0";
+        if (returnloc) {
+            req += "&wreply=";
+            if (*returnloc == '/') {
+                string s(returnloc);
+                httpRequest.absolutize(s);
+                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(s.c_str());
+            }
+            else {
+                req += XMLToolingConfig::getConfig().getURLEncoder()->encode(returnloc);
+            }
+        }
+        ret.second = httpResponse.sendRedirect(req.c_str());
+        ret.first = true;
+
+        if (session) {
+            sessionLocker.assign();
+            session = nullptr;
+            application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
+        }
+    }
+    catch (MetadataException& mex) {
+        // Less noise for IdPs that don't support logout
+        m_log.info("unable to issue ADFS logout request: %s", mex.what());
+    }
+    catch (std::exception& ex) {
+        m_log.error("error issuing ADFS logout request: %s", ex.what());
+    }
+
+    return ret;
+#else
+    throw ConfigurationException("Cannot perform logout using lite version of shibsp library.");
+#endif
+}
+
+pair<bool,long> ADFSLogout::run(SPRequest& request, bool isHandler) const
+{
+    // Defer to base class for front-channel loop first.
+    // This won't initiate the loop, only continue/end it.
+    pair<bool,long> ret = LogoutHandler::run(request, isHandler);
+    if (ret.first)
+        return ret;
+
+    // wa parameter indicates the "action" to perform
+    bool returning = false;
+    const char* param = request.getParameter("wa");
+    if (param) {
+        if (!strcmp(param, "wsignin1.0"))
+            return m_login.run(request, isHandler);
+        else if (strcmp(param, "wsignout1.0") && strcmp(param, "wsignoutcleanup1.0"))
+            throw FatalProfileException("Unsupported WS-Federation action parameter ($1).", params(1, param));
+    }
+    else if (strcmp(request.getMethod(),"GET") || !request.getParameter("notifying"))
+        throw FatalProfileException("Unsupported request to ADFS protocol endpoint.");
+    else
+        returning = true;
+
+    param = request.getParameter("wreply");
+    const Application& app = request.getApplication();
+
+    if (!returning) {
+        // Pass control to the first front channel notification point, if any.
+        map<string,string> parammap;
+        if (param)
+            parammap["wreply"] = param;
+        pair<bool,long> result = notifyFrontChannel(app, request, request, &parammap);
+        if (result.first)
+            return result;
+    }
+
+    // Best effort on back channel and to remove the user agent's session.
+    string session_id = app.getServiceProvider().getSessionCache()->active(app, request);
+    if (!session_id.empty()) {
+        vector<string> sessions(1,session_id);
+        notifyBackChannel(app, request.getRequestURL(), sessions, false);
+        try {
+            app.getServiceProvider().getSessionCache()->remove(app, request, &request);
+        }
+        catch (std::exception& ex) {
+            m_log.error("error removing session (%s): %s", session_id.c_str(), ex.what());
+        }
+    }
+
+    if (param) {
+        if (*param == '/') {
+            string p(param);
+            request.absolutize(p);
+            return make_pair(true, request.sendRedirect(p.c_str()));
+        }
+        else {
+            app.limitRedirect(request, param);
+            return make_pair(true, request.sendRedirect(param));
+        }
+    }
+    return sendLogoutPage(app, request, request, "global");
+}
diff --git a/apache/mod_shib.cpp b/apache/mod_shib.cpp
index 733d7e0..9bd6c18 100644
--- a/apache/mod_shib.cpp
+++ b/apache/mod_shib.cpp
@@ -1,2314 +1,2314 @@
-/**
- * Licensed to the University Corporation for Advanced Internet
- * Development, Inc. (UCAID) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for
- * additional information regarding copyright ownership.
- *
- * UCAID licenses this file to you 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
- *
- * 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.
- */
-
-/**
- * mod_shib.cpp
- *
- * Apache module implementation.
- */
-
-#define SHIBSP_LITE
-
-#ifdef SOLARIS2
-#undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
-#endif
-
-#ifdef WIN32
-# define _CRT_NONSTDC_NO_DEPRECATE 1
-# define _CRT_SECURE_NO_DEPRECATE 1
-#endif
-
-#include <shibsp/exceptions.h>
-#include <shibsp/AbstractSPRequest.h>
-#include <shibsp/AccessControl.h>
-#include <shibsp/GSSRequest.h>
-#include <shibsp/RequestMapper.h>
-#include <shibsp/SPConfig.h>
-#include <shibsp/ServiceProvider.h>
-#include <shibsp/SessionCache.h>
-#include <shibsp/attribute/Attribute.h>
-
-#include <xercesc/util/XMLUniDefs.hpp>
-#include <xercesc/util/regx/RegularExpression.hpp>
-#include <xmltooling/XMLToolingConfig.h>
-#include <xmltooling/util/NDC.h>
-#include <xmltooling/util/ParserPool.h>
-#include <xmltooling/util/Threads.h>
-#include <xmltooling/util/XMLConstants.h>
-#include <xmltooling/util/XMLHelper.h>
-
-#ifdef WIN32
-# include <winsock2.h>
-# include <ws2tcpip.h>
-#endif
-
-#undef _XPG4_2
-
-#include <set>
-#include <memory>
-#include <fstream>
-#include <stdexcept>
-#include <boost/lexical_cast.hpp>
-
-// Apache specific header files
-#include <httpd.h>
-#include <http_config.h>
-#include <http_protocol.h>
-#include <http_main.h>
-#define CORE_PRIVATE
-#include <http_core.h>
-#include <http_log.h>
-#include <http_request.h>
-
-#ifndef SHIB_APACHE_13
-#include <apr_buckets.h>
-#include <apr_strings.h>
-#include <apr_pools.h>
-#endif
-
-#ifdef SHIB_APACHE_24
-#include <mod_auth.h>
-#endif
-
-#include <cstddef>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>		// for getpid()
-#endif
-
-using namespace shibsp;
-using namespace xmltooling;
-using namespace boost;
-using namespace std;
-using xercesc::RegularExpression;
-using xercesc::XMLException;
-
-#ifdef APLOG_USE_MODULE
-    extern "C" module AP_MODULE_DECLARE_DATA mod_shib;
-    static int* const aplog_module_index = &(mod_shib.module_index);
-#else
-    extern "C" module MODULE_VAR_EXPORT mod_shib;
-#endif
-
-namespace {
-    char* g_szSHIBConfig = nullptr;
-    char* g_szSchemaDir = nullptr;
-    char* g_szPrefix = nullptr;
-    SPConfig* g_Config = nullptr;
-    string g_unsetHeaderValue,g_spoofKey;
-    bool g_checkSpoofing = true;
-    bool g_catchAll = false;
-#ifndef SHIB_APACHE_13
-    char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
-#endif
-    static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
-}
-
-/* Apache 2.2.x headers must be accumulated and set in the output filter.
-   Apache 2.0.49+ supports the filter method.
-   Apache 1.3.x and lesser 2.0.x must write the headers directly. */
-
-#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
-#define SHIB_DEFERRED_HEADERS
-#endif
-
-/********************************************************************************/
-// Basic Apache Configuration code.
-//
-
-// per-server module configuration structure
-struct shib_server_config
-{
-    char* szScheme;
-    int bCompatValidUser;
-};
-
-// creates the per-server configuration
-extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
-{
-    shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
-    sc->szScheme = nullptr;
-    sc->bCompatValidUser = -1;
-    return sc;
-}
-
-// overrides server configuration in virtual servers
-extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
-{
-    shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
-    shib_server_config* parent=(shib_server_config*)base;
-    shib_server_config* child=(shib_server_config*)sub;
-
-    if (child->szScheme)
-        sc->szScheme=ap_pstrdup(p,child->szScheme);
-    else if (parent->szScheme)
-        sc->szScheme=ap_pstrdup(p,parent->szScheme);
-    else
-        sc->szScheme=nullptr;
-
-    sc->bCompatValidUser = ((child->bCompatValidUser==-1) ? parent->bCompatValidUser : child->bCompatValidUser);
-
-    return sc;
-}
-
-// per-dir module configuration structure
-struct shib_dir_config
-{
-    SH_AP_TABLE* tSettings; // generic table of extensible settings
-
-    // RM Configuration
-#ifdef SHIB_APACHE_24
-    int bRequestMapperAuthz;// support RequestMapper AccessControl plugins
-#else
-    char* szAuthGrpFile;    // Auth GroupFile name
-	char* szAccessControl;	// path to "external" AccessControl plugin file
-    int bRequireAll;        // all "known" require directives must match, otherwise OR logic
-    int bAuthoritative;     // allow htaccess plugin to DECLINE when authz fails
-    int bCompatWith24;      // support 2.4-reserved require logic for compatibility
-#endif
-
-    // Content Configuration
-    char* szApplicationId;  // Shib applicationId value
-    char* szRequireWith;    // require a session using a specific initiator?
-    char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
-    int bOff;               // flat-out disable all Shib processing
-    int bBasicHijack;       // activate for AuthType Basic?
-    int bRequireSession;    // require a session?
-    int bExportAssertion;   // export SAML assertion to the environment?
-    int bUseEnvVars;        // use environment?
-    int bUseHeaders;        // use headers?
-    int bExpireRedirects;   // expire redirects?
-};
-
-// creates per-directory config structure
-extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
-{
-    shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
-    dc->tSettings = nullptr;
-#ifdef SHIB_APACHE_24
-    dc->bRequestMapperAuthz = -1;
-#else
-    dc->szAuthGrpFile = nullptr;
-	dc->szAccessControl = nullptr;
-    dc->bRequireAll = -1;
-    dc->bAuthoritative = -1;
-    dc->bCompatWith24 = -1;
-#endif
-    dc->szApplicationId = nullptr;
-    dc->szRequireWith = nullptr;
-    dc->szRedirectToSSL = nullptr;
-    dc->bOff = -1;
-    dc->bBasicHijack = -1;
-    dc->bRequireSession = -1;
-    dc->bExportAssertion = -1;
-    dc->bUseEnvVars = -1;
-    dc->bUseHeaders = -1;
-    dc->bExpireRedirects = -1;
-    return dc;
-}
-
-// overrides server configuration in directories
-extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
-{
-    shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
-    shib_dir_config* parent=(shib_dir_config*)base;
-    shib_dir_config* child=(shib_dir_config*)sub;
-
-    // The child supersedes any matching table settings in the parent.
-    dc->tSettings = nullptr;
-    if (parent->tSettings)
-        dc->tSettings = ap_copy_table(p, parent->tSettings);
-    if (child->tSettings) {
-        if (dc->tSettings)
-            ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
-        else
-            dc->tSettings = ap_copy_table(p, child->tSettings);
-    }
-
-#ifdef SHIB_APACHE_24
-    dc->bRequestMapperAuthz = ((child->bRequestMapperAuthz==-1) ? parent->bRequestMapperAuthz : child->bRequestMapperAuthz);
-#else
-    if (child->szAuthGrpFile)
-        dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
-    else if (parent->szAuthGrpFile)
-        dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
-    else
-        dc->szAuthGrpFile=nullptr;
-
-	if (child->szAccessControl)
-        dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
-    else if (parent->szAccessControl)
-        dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
-    else
-        dc->szAccessControl=nullptr;
-#endif
-
-    if (child->szApplicationId)
-        dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
-    else if (parent->szApplicationId)
-        dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
-    else
-        dc->szApplicationId=nullptr;
-
-    if (child->szRequireWith)
-        dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
-    else if (parent->szRequireWith)
-        dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
-    else
-        dc->szRequireWith=nullptr;
-
-    if (child->szRedirectToSSL)
-        dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
-    else if (parent->szRedirectToSSL)
-        dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
-    else
-        dc->szRedirectToSSL=nullptr;
-
-    dc->bOff = ((child->bOff==-1) ? parent->bOff : child->bOff);
-    dc->bBasicHijack = ((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
-    dc->bRequireSession = ((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
-    dc->bExportAssertion = ((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
-#ifndef SHIB_APACHE_24
-    dc->bRequireAll = ((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
-    dc->bAuthoritative = ((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
-    dc->bCompatWith24 = ((child->bCompatWith24==-1) ? parent->bCompatWith24 : child->bCompatWith24);
-#endif
-    dc->bUseEnvVars = ((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
-    dc->bUseHeaders = ((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
-    dc->bExpireRedirects = ((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
-    return dc;
-}
-
-class ShibTargetApache; // forward decl
-
-// per-request module structure
-struct shib_request_config
-{
-    SH_AP_TABLE* env;        // environment vars
-#ifdef SHIB_DEFERRED_HEADERS
-    SH_AP_TABLE* hdr_out;    // headers to browser
-#endif
-#ifndef SHIB_APACHE_13
-    ShibTargetApache* sta;  // SP per-request structure wrapped around Apache's request
-#endif
-};
-
-// create or return a request record
-static shib_request_config* get_request_config(request_rec *r)
-{
-    shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-    if (rc) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config called redundantly");
-    }
-    else {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config created per-request structure");
-        rc = (shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
-        memset(rc, 0, sizeof(shib_request_config));
-        ap_set_module_config(r->request_config, &mod_shib, rc);
-    }
-    return rc;
-}
-
-class ShibTargetApache : public AbstractSPRequest
-#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
-    , public GSSRequest
-#endif
-{
-  mutable string m_body;
-  mutable bool m_gotBody,m_firsttime;
-  mutable vector<string> m_certs;
-  set<string> m_allhttp;
-#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
-  mutable gss_name_t m_gssname;
-#endif
-
-public:
-  bool m_handler;
-  request_rec* m_req;
-  shib_dir_config* m_dc;
-  shib_server_config* m_sc;
-  shib_request_config* m_rc;
-
-  ShibTargetApache(request_rec* req) : AbstractSPRequest(SHIBSP_LOGCAT ".Apache"),
-        m_gotBody(false),m_firsttime(true),
-#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
-        m_gssname(GSS_C_NO_NAME),
-#endif
-        m_handler(false), m_req(req), m_dc(nullptr), m_sc(nullptr), m_rc(nullptr) {
-  }
-  virtual ~ShibTargetApache() {
-#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
-    if (m_gssname != GSS_C_NO_NAME) {
-        OM_uint32 minor;
-        gss_release_name(&minor, &m_gssname);
-    }
-#endif
-  }
-
-  bool isInitialized() const {
-      return (m_sc != nullptr);
-  }
-
-  bool init(bool handler, bool check_user) {
-    m_handler = handler;
-    if (m_sc)
-        return !check_user; // only initialize once
-    m_sc = (shib_server_config*)ap_get_module_config(m_req->server->module_config, &mod_shib);
-    m_dc = (shib_dir_config*)ap_get_module_config(m_req->per_dir_config, &mod_shib);
-    m_rc = (shib_request_config*)ap_get_module_config(m_req->request_config, &mod_shib);
-
-    setRequestURI(m_req->unparsed_uri);
-
-    if (check_user && m_dc->bUseHeaders == 1) {
-        // Try and see if this request was already processed, to skip spoof checking.
-        if (!ap_is_initial_req(m_req)) {
-            m_firsttime = false;
-        }
-        else if (!g_spoofKey.empty()) {
-            const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
-            if (hdr && g_spoofKey == hdr)
-                m_firsttime = false;
-        }
-        if (!m_firsttime)
-            log(SPDebug, "shib_check_user running more than once");
-    }
-    return true;
-  }
-
-  const char* getScheme() const {
-    return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
-  }
-  bool isSecure() const {
-      return HTTPRequest::isSecure();
-  }
-  const char* getHostname() const {
-#ifdef SHIB_APACHE_24
-      return ap_get_server_name_for_url(m_req);
-#else
-      return ap_get_server_name(m_req);
-#endif
-  }
-  int getPort() const {
-    return ap_get_server_port(m_req);
-  }
-  const char* getMethod() const {
-    return m_req->method;
-  }
-  string getContentType() const {
-    const char* type = ap_table_get(m_req->headers_in, "Content-Type");
-    return type ? type : "";
-  }
-  long getContentLength() const {
-      // Apache won't expose content length until the body's read.
-      if (!m_gotBody) {
-          getRequestBody();
-      }
-      return m_body.length();
-  }
-  string getRemoteAddr() const {
-    string ret = AbstractSPRequest::getRemoteAddr();
-    if (!ret.empty())
-        return ret;
-#ifdef SHIB_APACHE_24
-    return m_req->useragent_ip;
-#else
-    return m_req->connection->remote_ip;
-#endif
-  }
-  void log(SPLogLevel level, const string& msg) const {
-    AbstractSPRequest::log(level,msg);
-    ap_log_rerror(
-        APLOG_MARK,
-        (level == SPDebug ? APLOG_DEBUG :
-        (level == SPInfo ? APLOG_INFO :
-        (level == SPWarn ? APLOG_WARNING :
-        (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
-        SH_AP_R(m_req),
-        "%s",
-        msg.c_str()
-        );
-  }
-  const char* getQueryString() const { return m_req->args; }
-  const char* getRequestBody() const {
-    if (m_gotBody || m_req->method_number==M_GET)
-        return m_body.c_str();
-#ifdef SHIB_APACHE_13
-    // Read the posted data
-    if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
-        m_gotBody=true;
-        log(SPError, "Apache function (setup_client_block) failed while reading request body.");
-        return m_body.c_str();
-    }
-    if (!ap_should_client_block(m_req)) {
-        m_gotBody=true;
-        log(SPError, "Apache function (should_client_block) failed while reading request body.");
-        return m_body.c_str();
-    }
-    if (m_req->remaining > 1024*1024)
-        throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
-    m_gotBody=true;
-    int len;
-    char buff[HUGE_STRING_LEN];
-    ap_hard_timeout("[mod_shib] getRequestBody", m_req);
-    while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
-      ap_reset_timeout(m_req);
-      m_body.append(buff, len);
-    }
-    ap_kill_timeout(m_req);
-#else
-    const char *data;
-    apr_size_t len;
-    int seen_eos = 0;
-    apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
-    do {
-        apr_bucket *bucket;
-        apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
-        if (rv != APR_SUCCESS) {
-            log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
-            break;
-        }
-
-        for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
-            if (APR_BUCKET_IS_EOS(bucket)) {
-                seen_eos = 1;
-                break;
-            }
-
-            /* We can't do much with this. */
-            if (APR_BUCKET_IS_FLUSH(bucket))
-                continue;
-
-            /* read */
-            apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
-            if (len > 0)
-                m_body.append(data, len);
-        }
-        apr_brigade_cleanup(bb);
-    } while (!seen_eos);
-    apr_brigade_destroy(bb);
-    m_gotBody=true;
-#endif
-    return m_body.c_str();
-  }
-  const char* getParameter(const char* name) const {
-      return AbstractSPRequest::getParameter(name);
-  }
-  vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
-      return AbstractSPRequest::getParameters(name, values);
-  }
-  void clearHeader(const char* rawname, const char* cginame) {
-    if (m_dc->bUseHeaders == 1) {
-       // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
-        if (g_checkSpoofing && m_firsttime) {
-            if (m_allhttp.empty()) {
-                // First time, so populate set with "CGI" versions of client-supplied headers.
-#ifdef SHIB_APACHE_13
-                array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
-                table_entry *hdrs = (table_entry *) hdrs_arr->elts;
-#else
-                const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
-                const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
-#endif
-                for (int i = 0; i < hdrs_arr->nelts; ++i) {
-                    if (!hdrs[i].key)
-                        continue;
-                    string cgiversion("HTTP_");
-                    const char* pch = hdrs[i].key;
-                    while (*pch) {
-                        cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
-                        pch++;
-                    }
-                    m_allhttp.insert(cgiversion);
-                }
-            }
-
-            if (m_allhttp.count(cginame) > 0)
-                throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
-        }
-        ap_table_unset(m_req->headers_in, rawname);
-        ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
-    }
-  }
-  void setHeader(const char* name, const char* value) {
-    if (m_dc->bUseEnvVars != 0) {
-       if (!m_rc) {
-          // this happens on subrequests
-          // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
-          m_rc = get_request_config(m_req);
-       }
-       if (!m_rc->env)
-           m_rc->env = ap_make_table(m_req->pool, 10);
-       // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
-       ap_table_set(m_rc->env, name, value ? value : "");
-    }
-    if (m_dc->bUseHeaders == 1)
-       ap_table_set(m_req->headers_in, name, value);
-  }
-  string getHeader(const char* name) const {
-    const char* hdr = ap_table_get(m_req->headers_in, name);
-    return string(hdr ? hdr : "");
-  }
-  string getSecureHeader(const char* name) const {
-    if (m_dc->bUseEnvVars != 0) {
-       const char *hdr;
-       if (m_rc && m_rc->env)
-           hdr = ap_table_get(m_rc->env, name);
-       else
-           hdr = nullptr;
-       return string(hdr ? hdr : "");
-    }
-    return getHeader(name);
-  }
-  void setRemoteUser(const char* user) {
-      SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
-      if (m_dc->bUseHeaders == 1) {
-          if (user) {
-              ap_table_set(m_req->headers_in, "REMOTE_USER", user);
-          }
-          else {
-              ap_table_unset(m_req->headers_in, "REMOTE_USER");
-              ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
-          }
-      }
-  }
-  string getRemoteUser() const {
-    return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
-  }
-  void setAuthType(const char* authtype) {
-      if (authtype && m_dc->bBasicHijack == 1)
-          authtype = "Basic";
-      SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
-  }
-  string getAuthType() const {
-    return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
-  }
-  void setContentType(const char* type) {
-      m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
-  }
-  void setResponseHeader(const char* name, const char* value) {
-    HTTPResponse::setResponseHeader(name, value);
-    if (name) {
-#ifdef SHIB_DEFERRED_HEADERS
-        if (!m_rc) {
-            // this happens on subrequests
-            m_rc = get_request_config(m_req);
-        }
-        if (m_handler) {
-            if (!m_rc->hdr_out) {
-                m_rc->hdr_out = ap_make_table(m_req->pool, 5);
-            }
-            ap_table_add(m_rc->hdr_out, name, value);
-        }
-        else
-#endif
-            ap_table_add(m_req->err_headers_out, name, value);
-    }
-  }
-  long sendResponse(istream& in, long status) {
-    if (status != XMLTOOLING_HTTP_STATUS_OK)
-        m_req->status = status;
-    ap_send_http_header(m_req);
-    char buf[1024];
-    while (in) {
-        in.read(buf,1024);
-        ap_rwrite(buf,in.gcount(),m_req);
-    }
-#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24))
-    if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
-        return status;
-#endif
-    return DONE;
-  }
-  long sendRedirect(const char* url) {
-    HTTPResponse::sendRedirect(url);
-    ap_table_set(m_req->headers_out, "Location", url);
-    if (m_dc->bExpireRedirects != 0) {
-        ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
-        ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
-    }
-    return REDIRECT;
-  }
-  const vector<string>& getClientCertificates() const {
-      if (m_certs.empty()) {
-          const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
-          if (cert)
-              m_certs.push_back(cert);
-          int i = 0;
-          do {
-              cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
-              if (cert)
-                  m_certs.push_back(cert);
-          } while (cert);
-      }
-      return m_certs;
-  }
-  long returnDecline(void) { return DECLINED; }
-  long returnOK(void) { return OK; }
-#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
-  gss_ctx_id_t getGSSContext() const {
-    gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
-    apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
-    return ctx;
-  }
-  gss_name_t getGSSName() const {
-      if (m_gssname == GSS_C_NO_NAME) {
-          gss_ctx_id_t ctx = getGSSContext();
-          if (ctx != GSS_C_NO_CONTEXT) {
-              OM_uint32 minor;
-              OM_uint32 major = gss_inquire_context(&minor, ctx, &m_gssname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
-              if (major != GSS_S_COMPLETE)
-                  m_gssname = GSS_C_NO_NAME;
-          }
-      }
-      return m_gssname;
-  }
-  #endif
-};
-
-/********************************************************************************/
-// Apache hooks
-
-#ifndef SHIB_APACHE_13
-extern "C" apr_status_t shib_request_cleanup(void* rc)
-{
-    if (rc && reinterpret_cast<shib_request_config*>(rc)->sta) {
-        delete reinterpret_cast<ShibTargetApache*>(reinterpret_cast<shib_request_config*>(rc)->sta);
-        reinterpret_cast<shib_request_config*>(rc)->sta = nullptr;
-    }
-    return APR_SUCCESS;
-}
-#endif
-
-// Initial look at a request - create the per-request structure if need be
-static int shib_post_read(request_rec *r)
-{
-    shib_request_config* rc = get_request_config(r);
-#ifdef SHIB_APACHE_24
-    if (!rc->sta) {
-        rc->sta = new ShibTargetApache(r);
-        apr_pool_cleanup_register(r->pool, rc, shib_request_cleanup, apr_pool_cleanup_null);
-    }
-#endif
-    return DECLINED;
-}
-
-// Performs authentication and enforce session requirements.
-// Also does header/env export from session, and will dispatch
-// SP handler requests if it detects a handler URL.
-extern "C" int shib_check_user(request_rec* r)
-{
-    // Short-circuit entirely?
-    if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
-        return DECLINED;
-
-    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user entered in pid (%d)", (int)getpid());
-
-    string threadid("[");
-    threadid += lexical_cast<string>(getpid()) + "] shib_check_user";
-    xmltooling::NDC ndc(threadid.c_str());
-
-    try {
-#ifndef SHIB_APACHE_24
-        ShibTargetApache sta(r);
-        ShibTargetApache* psta = &sta;
-#else
-        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        if (!rc || !rc->sta) {
-            ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user found no per-request structure");
-            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
-            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        }
-        ShibTargetApache* psta = rc->sta;
-#endif
-        if (!psta->init(false, true)) {
-            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user unable to initialize SP request object");
-            return SERVER_ERROR;
-        }
-
-        // Check user authentication and export information, then set the handler bypass
-        pair<bool,long> res = psta->getServiceProvider().doAuthentication(*psta, true);
-        apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
-        // If directed, install a spoof key to recognize when we've already cleared headers.
-        if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders == 1))
-            ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
-        if (res.first) {
-#ifdef SHIB_APACHE_24
-            // This is insane, but Apache's internal request.c logic insists that an auth module
-            // returning OK MUST set r->user to avoid a failure. But they check for NULL and not
-            // for an empty string. If this turns out to cause trouble, there's no solution except
-            // to set a dummy ID any time it's not set.
-            if (res.second == OK && !r->user)
-                r->user = "";
-#endif
-            return res.second;
-        }
-
-        // user auth was okay -- export the session data now
-        res = psta->getServiceProvider().doExport(*psta);
-        if (res.first) {
-#ifdef SHIB_APACHE_24
-            // See above for explanation of this hack.
-            if (res.second == OK && !r->user)
-                r->user = "";
-#endif
-            return res.second;
-        }
-
-#ifdef SHIB_APACHE_24
-        // See above for explanation of this hack.
-        if (!r->user)
-            r->user = "";
-#endif
-        return OK;
-    }
-    catch (std::exception& e) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
-        return SERVER_ERROR;
-    }
-    catch (...) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
-        if (g_catchAll)
-            return SERVER_ERROR;
-        throw;
-    }
-}
-
-// Runs SP handler requests when invoked directly.
-extern "C" int shib_handler(request_rec* r)
-{
-    // Short-circuit entirely?
-    if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
-        return DECLINED;
-
-    string threadid("[");
-    threadid += lexical_cast<string>(getpid()) + "] shib_handler";
-    xmltooling::NDC ndc(threadid.c_str());
-
-#ifndef SHIB_APACHE_13
-    // With 2.x, this handler always runs, though last.
-    // We check if shib_check_user ran, because it will detect a handler request
-    // and dispatch it directly.
-    void* data;
-    apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
-    if (data==(const void*)42) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler skipped since check_user ran");
-        return DECLINED;
-    }
-#endif
-
-    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler entered in pid (%d): %s", (int)getpid(), r->handler);
-
-    try {
-#ifndef SHIB_APACHE_24
-        ShibTargetApache sta(r);
-        ShibTargetApache* psta = &sta;
-#else
-        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        if (!rc || !rc->sta) {
-            ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler found no per-request structure");
-            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
-            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        }
-        ShibTargetApache* psta = rc->sta;
-#endif
-        if (!psta->init(true, false)) {
-            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler unable to initialize SP request object");
-            return SERVER_ERROR;
-        }
-
-        pair<bool,long> res = psta->getServiceProvider().doHandler(*psta);
-        if (res.first) return res.second;
-
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not handle the request");
-        return SERVER_ERROR;
-    }
-    catch (std::exception& e) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
-        return SERVER_ERROR;
-    }
-    catch (...) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
-        if (g_catchAll)
-          return SERVER_ERROR;
-        throw;
-    }
-}
-
-// This performs authorization functions to limit access.
-// On all versions, this runs any RequestMap-attached plugins.
-// For pre-2.4 versions, the RequestMap will always find an htAccess plugin
-// that runs code to parse and enforce Apache Require rules.
-// On 2.4, we have to short-circuit that and let Apache run callbacks
-// for each Require rule we handle.
-extern "C" int shib_auth_checker(request_rec* r)
-{
-    // Short-circuit entirely?
-    shib_dir_config* dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
-    if (dc->bOff == 1
-#ifdef SHIB_APACHE_24
-        || dc->bRequestMapperAuthz == 0     // this allows for bypass of the full auth_checker hook if only htaccess is used
-#endif
-        ) {
-        return DECLINED;
-    }
-
-    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker entered in pid (%d)", (int)getpid());
-
-    string threadid("[");
-    threadid += lexical_cast<string>(getpid()) + "] shib_auth_checker";
-    xmltooling::NDC ndc(threadid.c_str());
-
-    try {
-#ifndef SHIB_APACHE_24
-        ShibTargetApache sta(r);
-        ShibTargetApache* psta = &sta;
-#else
-        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        if (!rc || !rc->sta) {
-            ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker found no per-request structure");
-            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
-            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-        }
-        ShibTargetApache* psta = rc->sta;
-#endif
-        if (!psta->init(false, false)) {
-            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker unable to initialize SP request object");
-            return SERVER_ERROR;
-        }
-
-        pair<bool,long> res = psta->getServiceProvider().doAuthorization(*psta);
-        if (res.first) return res.second;
-
-        // The SP method should always return true, so if we get this far, something unusual happened.
-        // Just let Apache (or some other module) decide what to do.
-        return DECLINED;
-    }
-    catch (std::exception& e) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
-        return SERVER_ERROR;
-    }
-    catch (...) {
-        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
-        if (g_catchAll)
-          return SERVER_ERROR;
-        throw;
-    }
-}
-
-// Overlays environment variables on top of subprocess table.
-extern "C" int shib_fixups(request_rec* r)
-{
-    shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
-    if (dc->bOff==1 || dc->bUseEnvVars==0)
-        return DECLINED;
-
-    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups entered in pid (%d)", (int)getpid());
-
-    shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-    if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
-        return DECLINED;
-
-    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups adding %d vars", ap_table_elts(rc->env)->nelts);
-    r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
-
-    return OK;
-}
-
-
-// Access control plugin that enforces pre-2.4 htaccess rules.
-// Post-2.4, we have to register individual methods to respond
-// to each require rule we want to handle, and have those call
-// into these methods directly.
-class htAccessControl : virtual public AccessControl
-{
-public:
-    htAccessControl() {}
-    ~htAccessControl() {}
-    Lockable* lock() {return this;}
-    void unlock() {}
-    aclresult_t authorized(const SPRequest& request, const Session* session) const;
-
-    aclresult_t doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const;
-    aclresult_t doUser(const ShibTargetApache& sta, const char* params) const;
-#ifndef SHIB_APACHE_24
-    aclresult_t doGroup(const ShibTargetApache& sta, const char* params) const;
-#endif
-    aclresult_t doAuthnContext(const ShibTargetApache& sta, const char* acRef, const char* params) const;
-    aclresult_t doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const;
-
-private:
-    bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
-};
-
-AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
-{
-    return new htAccessControl();
-}
-
-AccessControl::aclresult_t htAccessControl::doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const
-{
-	aclresult_t result = shib_acl_false;
-	try {
-        ifstream aclfile(plugin);
-        if (!aclfile)
-            throw ConfigurationException("Unable to open access control file ($1).", params(1, plugin));
-        xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
-		XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
-		static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
-        string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
-        if (t.empty())
-            throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
-        scoped_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
-		Locker acllock(aclplugin.get());
-		result = aclplugin->authorized(sta, session);
-	}
-	catch (std::exception& ex) {
-		sta.log(SPRequest::SPError, ex.what());
-	}
-    return result;
-}
-
-AccessControl::aclresult_t htAccessControl::doUser(const ShibTargetApache& sta, const char* params) const
-{
-    bool regexp = false;
-    bool negated = false;
-    while (*params) {
-        const char* w = ap_getword_conf(sta.m_req->pool, &params);
-        if (*w == '~') {
-            regexp = true;
-            continue;
-        }
-        else if (*w == '!') {
-            // A negated rule presumes success unless a match is found.
-            negated = true;
-            if (*(w+1) == '~')
-                regexp = true;
-            continue;
-        }
-
-        // Figure out if there's a match.
-        bool match = false;
-        if (regexp) {
-            try {
-                // To do regex matching, we have to convert from UTF-8.
-                auto_arrayptr<XMLCh> trans(fromUTF8(w));
-                RegularExpression re(trans.get());
-                auto_arrayptr<XMLCh> trans2(fromUTF8(sta.getRemoteUser().c_str()));
-                match = re.matches(trans2.get());
-            }
-            catch (XMLException& ex) {
-                auto_ptr_char tmp(ex.getMessage());
-                sta.log(SPRequest::SPError,
-                    string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
-            }
-        }
-        else if (sta.getRemoteUser() == w) {
-            match = true;
-        }
-
-        if (match) {
-            if (sta.isPriorityEnabled(SPRequest::SPDebug))
-                sta.log(SPRequest::SPDebug,
-                    string("htaccess: require user ") + (negated ? "rejecting (" : "accepting (") + sta.getRemoteUser() + ")");
-            return (negated ? shib_acl_false : shib_acl_true);
-        }
-    }
-    return (negated ? shib_acl_true : shib_acl_false);
-}
-
-#ifndef SHIB_APACHE_24
-static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
-{
-    SH_AP_CONFIGFILE* f;
-    SH_AP_TABLE* grps=ap_make_table(r->pool,15);
-    char l[MAX_STRING_LEN];
-    const char *group_name, *ll, *w;
-
-#ifdef SHIB_APACHE_13
-    if (!(f=ap_pcfg_openfile(r->pool, grpfile))) {
-#else
-    if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
-#endif
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, SH_AP_R(r), "groups_for_user: could not open group file: %s\n", grpfile);
-        return nullptr;
-    }
-
-    SH_AP_POOL* sp;
-#ifdef SHIB_APACHE_13
-    sp=ap_make_sub_pool(r->pool);
-#else
-    if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
-        ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
-            "groups_for_user: could not create a subpool");
-        return nullptr;
-    }
-#endif
-
-    while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
-        if ((*l=='#') || (!*l))
-            continue;
-        ll = l;
-        ap_clear_pool(sp);
-        group_name = ap_getword(sp,&ll,':');
-        while (*ll) {
-            w=ap_getword_conf(sp,&ll);
-            if (!strcmp(w,user)) {
-                ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
-                break;
-            }
-        }
-    }
-    ap_cfg_closefile(f);
-    ap_destroy_pool(sp);
-    return grps;
-}
-
-AccessControl::aclresult_t htAccessControl::doGroup(const ShibTargetApache& sta, const char* params) const
-{
-    SH_AP_TABLE* grpstatus = nullptr;
-    if (sta.m_dc->szAuthGrpFile) {
-        if (sta.isPriorityEnabled(SPRequest::SPDebug))
-            sta.log(SPRequest::SPDebug, string("htaccess plugin using groups file: ") + sta.m_dc->szAuthGrpFile);
-        grpstatus = groups_for_user(sta.m_req, sta.getRemoteUser().c_str(), sta.m_dc->szAuthGrpFile);
-    }
-
-    bool negated = false;
-    while (*params) {
-        const char* w = ap_getword_conf(sta.m_req->pool, &params);
-        if (*w == '!') {
-            // A negated rule presumes success unless a match is found.
-            negated = true;
-            continue;
-        }
-
-        if (grpstatus && ap_table_get(grpstatus, w)) {
-            // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
-            sta.log(SPRequest::SPDebug, string("htaccess: require group ") + (negated ? "rejecting (" : "accepting (") + w + ")");
-            return (negated ? shib_acl_false : shib_acl_true);
-        }
-    }
-
-    return (negated ? shib_acl_true : shib_acl_false);
-}
-#endif
-
-AccessControl::aclresult_t htAccessControl::doAuthnContext(const ShibTargetApache& sta, const char* ref, const char* params) const
-{
-    if (ref && *ref) {
-        bool regexp = false;
-        bool negated = false;
-        while (ref && *params) {
-            const char* w = ap_getword_conf(sta.m_req->pool, &params);
-            if (*w == '~') {
-                regexp = true;
-                continue;
-            }
-            else if (*w == '!') {
-                // A negated rule presumes success unless a match is found.
-                negated = true;
-                if (*(w+1) == '~')
-                    regexp = true;
-                continue;
-            }
-
-            // Figure out if there's a match.
-            bool match = false;
-            if (regexp) {
-                try {
-                    RegularExpression re(w);
-                    match = re.matches(ref);
-                }
-                catch (XMLException& ex) {
-                    auto_ptr_char tmp(ex.getMessage());
-                    sta.log(SPRequest::SPError,
-                        string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
-                }
-            }
-            else if (!strcmp(w, ref)) {
-                match = true;
-            }
-
-            if (match) {
-                if (sta.isPriorityEnabled(SPRequest::SPDebug))
-                    sta.log(SPRequest::SPDebug,
-                        string("htaccess: require authnContext ") + (negated ? "rejecting (" : "accepting (") + ref + ")");
-                return (negated ? shib_acl_false : shib_acl_true);
-            }
-        }
-        return (negated ? shib_acl_true : shib_acl_false);
-    }
-
-    if (sta.isPriorityEnabled(SPRequest::SPDebug))
-        sta.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
-    return shib_acl_false;
-}
-
-bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
-{
-    bool caseSensitive = attr->isCaseSensitive();
-    const vector<string>& vals = attr->getSerializedValues();
-    for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
-        if (re) {
-            auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
-            if (re->matches(trans.get())) {
-                if (request.isPriorityEnabled(SPRequest::SPDebug))
-                    request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": accepted");
-                return true;
-            }
-        }
-        else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
-            if (request.isPriorityEnabled(SPRequest::SPDebug))
-                request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
-            return true;
-        }
-        else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
-            request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
-        }
-    }
-    return false;
-}
-
-AccessControl::aclresult_t htAccessControl::doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const
-{
-#ifndef SHIB_APACHE_24
-    // Look for the new shib-attr placeholder and move past it.
-    if (sta.m_dc->bCompatWith24 == 1 && rule && !strcmp(rule, "shib-attr")) {
-        if (*params)
-            rule = ap_getword_conf(sta.m_req->pool, &params);
-    }
-#endif
-
-    // Find the attribute(s) matching the require rule.
-    pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
-        session->getIndexedAttributes().equal_range(rule ? rule : "");
-
-    bool regexp = false;
-    while (attrs.first != attrs.second && *params) {
-        const char* w = ap_getword_conf(sta.m_req->pool, &params);
-        if (*w == '~') {
-            regexp = true;
-            continue;
-        }
-
-        try {
-            scoped_ptr<RegularExpression> re;
-            if (regexp) {
-                auto_arrayptr<XMLCh> trans(fromUTF8(w));
-                re.reset(new xercesc::RegularExpression(trans.get()));
-            }
-                    
-            pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
-            for (; attrs2.first != attrs2.second; ++attrs2.first) {
-                if (checkAttribute(sta, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
-                    return shib_acl_true;
-                }
-            }
-        }
-        catch (XMLException& ex) {
-            auto_ptr_char tmp(ex.getMessage());
-            sta.log(SPRequest::SPError, string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
-        }
-    }
-    return shib_acl_false;
-}
-
-AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
-{
-#ifdef SHIB_APACHE_24
-    // We should never be invoked in 2.4 as an SP plugin.
-    throw ConfigurationException("Save my walrus!");
-#else
-    // Make sure the object is our type.
-    const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
-    if (!sta)
-        throw ConfigurationException("Request wrapper object was not of correct type.");
-
-    int m = sta->m_req->method_number;
-    bool method_restricted = false;
-    const char *t, *w;
-
-    const array_header* reqs_arr = ap_requires(sta->m_req);
-    if (!reqs_arr)
-        return shib_acl_indeterminate;  // should never happen
-
-	// Check for an "embedded" AccessControl plugin.
-	if (sta->m_dc->szAccessControl) {
-        aclresult_t result = doAccessControl(*sta, session, sta->m_dc->szAccessControl);
-        if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
-            // If we're not insisting that all rules be met, then we're done.
-            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
-            return shib_acl_true;
-        }
-        else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
-            // If we're insisting that all rules be met, which is not something Apache really handles well,
-            // then we either return false or indeterminate based on the authoritative option, which defaults on.
-            if (sta->m_dc->bAuthoritative != 0) {
-                request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
-                return shib_acl_false;
-            }
-
-            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
-            return shib_acl_indeterminate;
-        }
-    }
-
-    require_line* reqs = (require_line*)reqs_arr->elts;
-
-    for (int x = 0; x < reqs_arr->nelts; ++x) {
-        // This rule should be completely ignored, the method doesn't fit.
-        // The rule just doesn't exist for our purposes.
-        if (!(reqs[x].method_mask & (1 << m)))
-            continue;
-
-        method_restricted = true; // this lets us know at the end that at least one rule was potentially enforcable.
-
-        // Tracks status of this rule's evaluation.
-        bool status = false;
-
-        string remote_user = request.getRemoteUser();
-
-        t = reqs[x].requirement;
-        w = ap_getword_white(sta->m_req->pool, &t);
-
-        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.
-
-            // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
-            // This allows actual rules to dictate the result, since ShibAccessControl returned
-            // non-true, and if nothing else is used, access will be denied.
-            if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
-                // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
-                // or because there was no other AccessControl rule in place, so this may be the only
-                // rule in effect.
-                status = true;
-            }
-        }
-        else if (!strcmp(w,"valid-user") && session) {
-            request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
-            status = true;
-        }
-        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-session") && session) {
-            request.log(SPRequest::SPDebug, "htaccess: accepting shib-session based on active session");
-            status = true;
-        }
-        else if (!strcmp(w,"user") && !remote_user.empty()) {
-            status = (doUser(*sta, t) == shib_acl_true);
-        }
-        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-user") && !remote_user.empty()) {
-            status = (doUser(*sta, t) == shib_acl_true);
-        }
-        else if (!strcmp(w,"group")  && !remote_user.empty()) {
-            status = (doGroup(*sta, t) == shib_acl_true);
-        }
-        else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
-            const char* ref = !strcmp(w, "authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
-            status = (doAuthnContext(*sta, ref, t) == shib_acl_true);
-        }
-        else if (!session) {
-            request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
-        }
-        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-plugin")) {
-            w = ap_getword_conf(sta->m_req->pool, &t);
-            if (w) {
-                status = (doAccessControl(*sta, session, w) == shib_acl_true);
-            }
-        }
-        else {
-            status = (doShibAttr(*sta, session, w, t) == shib_acl_true);
-        }
-
-        // If status is false, we found a rule we couldn't satisfy.
-        // Could be an unknown rule to us, or it just didn't match.
-
-        if (status && sta->m_dc->bRequireAll != 1) {
-            // If we're not insisting that all rules be met, then we're done.
-            request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
-            return shib_acl_true;
-        }
-        else if (!status && sta->m_dc->bRequireAll == 1) {
-            // If we're insisting that all rules be met, which is not something Apache really handles well,
-            // then we either return false or indeterminate based on the authoritative option, which defaults on.
-            if (sta->m_dc->bAuthoritative != 0) {
-                request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
-                return shib_acl_false;
-            }
-
-            request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
-            return shib_acl_indeterminate;
-        }
-
-        // Otherwise, we keep going. If we're requring all, then we have to check every rule.
-        // If not we just didn't find a successful rule yet, so we keep going anyway.
-    }
-
-    // If we get here, we either "failed" or we're in require all mode (but not both).
-    // If no rules possibly apply or we insisted that all rules check out, then we're good.
-    if (!method_restricted) {
-        request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
-        return shib_acl_true;
-    }
-    else if (sta->m_dc->bRequireAll == 1) {
-        request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
-        return shib_acl_true;
-    }
-    else if (sta->m_dc->bAuthoritative != 0) {
-        request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
-        return shib_acl_false;
-    }
-
-    request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
-    return shib_acl_indeterminate;
-#endif
-}
-
-class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
-{
-public:
-    ApacheRequestMapper(const xercesc::DOMElement* e);
-    ~ApacheRequestMapper() {}
-    Lockable* lock() { return m_mapper->lock(); }
-    void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
-    Settings getSettings(const HTTPRequest& request) const;
-
-    const PropertySet* getParent() const { return nullptr; }
-    void setParent(const PropertySet*) {}
-    pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
-    pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
-    pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
-    pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
-    pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
-    void getAll(map<string,const char*>& properties) const;
-    const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
-    const xercesc::DOMElement* getElement() const;
-
-    const htAccessControl& getHTAccessControl() const { return m_htaccess; }
-
-private:
-    scoped_ptr<RequestMapper> m_mapper;
-    scoped_ptr<ThreadKey> m_staKey,m_propsKey;
-    mutable htAccessControl m_htaccess;
-};
-
-RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
-{
-    return new ApacheRequestMapper(e);
-}
-
-ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e)
-    : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
-        m_staKey(ThreadKey::create(nullptr)), m_propsKey(ThreadKey::create(nullptr))
-{
-}
-
-RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
-{
-    Settings s = m_mapper->getSettings(request);
-    m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
-    m_propsKey->setData((void*)s.first);
-    // Only return the htAccess plugin for pre-2.4 servers.
-#ifdef SHIB_APACHE_24
-    return pair<const PropertySet*,AccessControl*>(this, s.second);
-#else
-    return pair<const PropertySet*,AccessControl*>(this, s.second ? s.second : &m_htaccess);
-#endif
-}
-
-pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
-{
-    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    if (sta && !ns) {
-        // Override Apache-settable boolean properties.
-        if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
-            return make_pair(true, sta->m_dc->bRequireSession==1);
-        else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
-            return make_pair(true, sta->m_dc->bExportAssertion==1);
-        else if (sta->m_dc->tSettings) {
-            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
-            if (prop)
-                return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
-        }
-    }
-    return s ? s->getBool(name,ns) : make_pair(false,false);
-}
-
-pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
-{
-    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    if (sta && !ns) {
-        // Override Apache-settable string properties.
-        if (name && !strcmp(name,"authType")) {
-            const char* auth_type = ap_auth_type(sta->m_req);
-            if (auth_type) {
-                // Check for Basic Hijack
-                if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
-                    auth_type = "shibboleth";
-                return make_pair(true, auth_type);
-            }
-        }
-        else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
-            return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
-        else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
-            return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
-        else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
-            return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
-        else if (sta->m_dc->tSettings) {
-            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
-            if (prop)
-                return make_pair(true, prop);
-        }
-    }
-    return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
-}
-
-pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
-{
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
-}
-
-pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
-{
-    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    if (sta && !ns) {
-        // Override Apache-settable int properties.
-        if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
-            return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
-        else if (sta->m_dc->tSettings) {
-            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
-            if (prop)
-                return pair<bool,unsigned int>(true, atoi(prop));
-        }
-    }
-    return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
-}
-
-pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
-{
-    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    if (sta && !ns) {
-        // Override Apache-settable int properties.
-        if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
-            return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
-        else if (sta->m_dc->tSettings) {
-            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
-            if (prop)
-                return make_pair(true, atoi(prop));
-        }
-    }
-    return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
-}
-
-static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
-{
-    reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
-    return 1;
-}
-
-void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
-{
-    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-
-    if (s)
-        s->getAll(properties);
-    if (!sta)
-        return;
-
-    const char* auth_type=ap_auth_type(sta->m_req);
-    if (auth_type) {
-        // Check for Basic Hijack
-        if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
-            auth_type = "shibboleth";
-        properties["authType"] = auth_type;
-    }
-
-    if (sta->m_dc->szApplicationId)
-        properties["applicationId"] = sta->m_dc->szApplicationId;
-    if (sta->m_dc->szRequireWith)
-        properties["requireSessionWith"] = sta->m_dc->szRequireWith;
-    if (sta->m_dc->szRedirectToSSL)
-        properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
-    if (sta->m_dc->bRequireSession != 0)
-        properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
-    if (sta->m_dc->bExportAssertion != 0)
-        properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
-
-    if (sta->m_dc->tSettings)
-        ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
-}
-
-const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
-{
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getPropertySet(name,ns) : nullptr;
-}
-
-const xercesc::DOMElement* ApacheRequestMapper::getElement() const
-{
-    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getElement() : nullptr;
-}
-
-// Authz callbacks for Apache 2.4
-// For some reason, these get run twice for each request, once before hooks like check_user, etc.
-// and once after. The first time through, the request object exists, but isn't initialized.
-// The other case is subrequests of some kinds: then post_read doesn't run, and the objects
-// themselves don't exist. We do deferred creation of the objects in check_user to fix that case.
-// In each screwed up case, we return "denied" so that nothing bad happens.
-#ifdef SHIB_APACHE_24
-pair<ShibTargetApache*,authz_status> shib_base_check_authz(request_rec* r)
-{
-    shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
-    if (!rc || !rc->sta) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found no per-request structure");
-        return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
-    }
-    else if (!rc->sta->isInitialized()) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found uninitialized request object");
-        return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
-    }
-    return make_pair(rc->sta, AUTHZ_GRANTED);
-}
-
-extern "C" authz_status shib_shibboleth_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-    return AUTHZ_GRANTED;
-}
-
-extern "C" authz_status shib_session_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    try {
-        Session* session = sta.first->getSession(false, true, false);
-        Locker slocker(session, false);
-        if (session) {
-            sta.first->log(SPRequest::SPDebug, "htaccess: accepting shib-session/valid-user based on active session");
-            return AUTHZ_GRANTED;
-        }
-    }
-    catch (std::exception& e) {
-        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
-    }
-
-    sta.first->log(SPRequest::SPDebug, "htaccess: denying shib-access/valid-user rule, no active session");
-    return AUTHZ_DENIED_NO_USER;
-}
-
-extern "C" authz_status shib_validuser_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
-    // For now, added a command to restore "normal" semantics for valid-user so that combined deployments can
-    // use valid-user for non-Shibboleth cases and shib-session for the Shibboleth semantic.
-
-    // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
-    // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
-    // that setting from the ServiceProvider class..
-
-    shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
-    if (sc->bCompatValidUser != 1) {
-        return shib_session_check_authz(r, require_line, nullptr);
-    }
-
-    // Reproduce mod_authz_user version...
-
-    if (!r->user) {
-        return AUTHZ_DENIED_NO_USER;
-    }
-
-    return AUTHZ_GRANTED;
-}
-
-extern "C" authz_status shib_ext_user_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
-    if (hta.doUser(*sta.first, require_line) == AccessControl::shib_acl_true)
-        return AUTHZ_GRANTED;
-    return AUTHZ_DENIED;
-}
-
-extern "C" authz_status shib_user_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
-    // For now, added a command to restore "normal" semantics for user rules so that combined deployments can
-    // use user for non-Shibboleth cases and shib-user for the Shibboleth semantic.
-
-    // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
-    // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
-    // that setting from the ServiceProvider class..
-
-    shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
-    if (sc->bCompatValidUser != 1) {
-        return shib_ext_user_check_authz(r, require_line, nullptr);
-    }
-
-    // Reproduce mod_authz_user version...
-
-    if (!r->user) {
-        return AUTHZ_DENIED_NO_USER;
-    }
- 	
-    const char* t = require_line;
-    const char *w;
-    while ((w = ap_getword_conf(r->pool, &t)) && w[0]) {
-        if (!strcmp(r->user, w)) {
-            return AUTHZ_GRANTED;
-        }
-    }
- 	
-    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01663)
-        "access to %s failed, reason: user '%s' does not meet "
-        "'require'ments for user to be allowed access",
-        r->uri, r->user);
- 	
-    return AUTHZ_DENIED;
-}
-
-extern "C" authz_status shib_acclass_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
-
-    try {
-        Session* session = sta.first->getSession(false, true, false);
-        Locker slocker(session, false);
-        if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextClassRef(), require_line) == AccessControl::shib_acl_true)
-            return AUTHZ_GRANTED;
-        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
-    }
-    catch (std::exception& e) {
-        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
-    }
-
-    return AUTHZ_GENERAL_ERROR;
-}
-
-extern "C" authz_status shib_acdecl_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
-
-    try {
-        Session* session = sta.first->getSession(false, true, false);
-        Locker slocker(session, false);
-        if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextDeclRef(), require_line) == AccessControl::shib_acl_true)
-            return AUTHZ_GRANTED;
-        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
-    }
-    catch (std::exception& e) {
-        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
-    }
-
-    return AUTHZ_GENERAL_ERROR;
-}
-
-extern "C" authz_status shib_attr_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
-
-    try {
-        Session* session = sta.first->getSession(false, true, false);
-        Locker slocker(session, false);
-        if (session) {
-            const char* rule = ap_getword_conf(r->pool, &require_line);
-            if (rule && hta.doShibAttr(*sta.first, session, rule, require_line) == AccessControl::shib_acl_true)
-                return AUTHZ_GRANTED;
-        }
-        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
-    }
-    catch (std::exception& e) {
-        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
-    }
-
-    return AUTHZ_GENERAL_ERROR;
-}
-
-extern "C" authz_status shib_plugin_check_authz(request_rec* r, const char* require_line, const void*)
-{
-    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
-    if (!sta.first)
-        return sta.second;
-
-    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
-
-    try {
-        Session* session = sta.first->getSession(false, true, false);
-        Locker slocker(session, false);
-        if (session) {
-            const char* config = ap_getword_conf(r->pool, &require_line);
-            if (config && hta.doAccessControl(*sta.first, session, config) == AccessControl::shib_acl_true)
-                return AUTHZ_GRANTED;
-        }
-        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
-    }
-    catch (std::exception& e) {
-        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
-    }
-
-    return AUTHZ_GENERAL_ERROR;
-}
-#endif
-
-// Command manipulation functions
-
-extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
-{
-    *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
-    return nullptr;
-}
-
-extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
-{
-    char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
-    size_t offset=(size_t)parms->info;
-    *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
-    return nullptr;
-}
-
-extern "C" const char* shib_set_server_flag_slot(cmd_parms* parms, void*, int arg)
-{
-    char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
-    size_t offset=(size_t)parms->info;
-    *((int*)(base + offset)) = arg;
-    return nullptr;
-}
-
-extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
-#ifdef SHIB_APACHE_13
-					     char* arg1, char* arg2
-#else
-					     void* arg1, const char* arg2
-#endif
-					     )
-{
-  ap_set_file_slot(parms, arg1, arg2);
-  return DECLINE_CMD;
-}
-
-extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
-{
-    if (!dc->tSettings)
-        dc->tSettings = ap_make_table(parms->pool, 4);
-    ap_table_set(dc->tSettings, arg1, arg2);
-    return nullptr;
-}
-
-#ifndef SHIB_APACHE_24
-extern "C" const char* shib_set_acl_slot(cmd_parms* params, shib_dir_config* dc, char* arg)
-{
-    bool absolute;
-    switch (*arg) {
-        case 0:
-            absolute = false;
-            break;
-        case '/':
-        case '\\':
-            absolute = true;
-            break;
-        case '.':
-            absolute = (*(arg+1) == '.' || *(arg+1) == '/' || *(arg+1) == '\\');
-            break;
-        default:
-            absolute = *(arg+1) == ':';
-    }
-
-    if (absolute || !params->path)
-        dc->szAccessControl = ap_pstrdup(params->pool, arg);
-    else
-        dc->szAccessControl = ap_pstrcat(params->pool, params->path, arg, NULL);
-    return nullptr;
-}
-#endif
-
-
-#ifdef SHIB_APACHE_13
-/*
- * shib_child_exit()
- *  Cleanup the (per-process) pool info.
- */
-extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
-{
-    if (g_Config) {
-        g_Config->term();
-        g_Config = nullptr;
-    }
-    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "child_exit: mod_shib shutdown in pid (%d)", (int)getpid());
-}
-#else
-/*
- * shib_exit()
- *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
- */
-extern "C" apr_status_t shib_exit(void* data)
-{
-    if (g_Config) {
-        g_Config->term();
-        g_Config = nullptr;
-    }
-    server_rec* s = reinterpret_cast<server_rec*>(data);
-    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "shib_exit: mod_shib shutdown in pid (%d)", (int)getpid());
-    return OK;
-}
-
-/*
- * shib_post_config()
- *  We do the library init/term work here for 2.x to reduce overhead and
- *  get default logging established before the fork happens.
- */
-apr_status_t shib_post_config(apr_pool_t* p, apr_pool_t*, apr_pool_t*, server_rec* s)
-{
-    // Initialize runtime components.
-    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"post_config: mod_shib initializing in pid (%d)", (int)getpid());
-
-    if (g_Config) {
-        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib already initialized");
-        return !OK;
-    }
-
-    g_Config = &SPConfig::getConfig();
-    g_Config->setFeatures(
-        SPConfig::Listener |
-        SPConfig::Caching |
-        SPConfig::RequestMapping |
-        SPConfig::InProcess |
-        SPConfig::Logging |
-        SPConfig::Handlers
-        );
-    if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib failed to initialize libraries");
-        return !OK;
-    }
-#ifndef SHIB_APACHE_24
-    g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
-#endif
-    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
-
-    // Set the cleanup handler, passing in the server_rec for logging.
-    apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
-
-    return OK;
-}
-
-#endif
-
-/*
- * shib_child_init()
- *  Things to do when the child process is initialized.
- *  We can't use post-config for all of it on 2.x because only the forking thread shows
- *  up in the child, losing the internal threads spun up by plugins in the SP.
- */
-#ifdef SHIB_APACHE_13
-extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
-#else
-extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
-#endif
-{
-    // Initialize runtime components.
-
-    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"child_init: mod_shib initializing in pid (%d)", (int)getpid());
-
-    // 2.x versions have already initialized the libraries.
-#ifdef SHIB_APACHE_13
-    if (g_Config) {
-        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib already initialized, exiting");
-        exit(1);
-    }
-
-    g_Config = &SPConfig::getConfig();
-    g_Config->setFeatures(
-        SPConfig::Listener |
-        SPConfig::Caching |
-        SPConfig::RequestMapping |
-        SPConfig::InProcess |
-        SPConfig::Logging |
-        SPConfig::Handlers
-        );
-    if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to initialize libraries");
-        exit(1);
-    }
-    g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
-    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
-#endif
-
-    // The config gets installed for all versions here due to the background thread/fork issues.
-    try {
-        if (!g_Config->instantiate(g_szSHIBConfig, true))
-            throw runtime_error("unknown error");
-    }
-    catch (std::exception& ex) {
-        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to load configuration: %s", ex.what());
-        g_Config->term();
-        exit(1);
-    }
-
-    ServiceProvider* sp = g_Config->getServiceProvider();
-    xmltooling::Locker locker(sp);
-    const PropertySet* props = sp->getPropertySet("InProcess");
-    if (props) {
-        pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
-        if (unsetValue.first)
-            g_unsetHeaderValue = unsetValue.second;
-        pair<bool,bool> flag=props->getBool("checkSpoofing");
-        g_checkSpoofing = !flag.first || flag.second;
-        if (g_checkSpoofing) {
-            unsetValue=props->getString("spoofKey");
-            if (unsetValue.first)
-                g_spoofKey = unsetValue.second;
-        }
-        flag=props->getBool("catchAll");
-        g_catchAll = flag.first && flag.second;
-    }
-
-    // Set the cleanup handler, passing in the server_rec for logging.
-    apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
-
-    ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib config initialized");
-}
-
-// Output filters
-#ifdef SHIB_DEFERRED_HEADERS
-static void set_output_filter(request_rec *r)
-{
-   ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
-}
-
-static void set_error_filter(request_rec *r)
-{
-   ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
-}
-
-static int _table_add(void *v, const char *key, const char *value)
-{
-    apr_table_addn((apr_table_t*)v, key, value);
-    return 1;
-}
-
-static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
-{
-    request_rec *r = f->r;
-    shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
-
-    if (rc && rc->hdr_out) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "output_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
-        // can't use overlap call because it will collapse Set-Cookie headers
-        //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
-        apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
-    }
-
-    /* remove ourselves from the filter chain */
-    ap_remove_output_filter(f);
-
-    /* send the data up the stack */
-    return ap_pass_brigade(f->next,in);
-}
-
-static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
-{
-    request_rec *r = f->r;
-    shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
-
-    if (rc && rc->hdr_out) {
-        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "error_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
-        // can't use overlap call because it will collapse Set-Cookie headers
-        //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
-        apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
-    }
-
-    /* remove ourselves from the filter chain */
-    ap_remove_output_filter(f);
-
-    /* send the data up the stack */
-    return ap_pass_brigade(f->next,in);
-}
-#endif // SHIB_DEFERRED_HEADERS
-
-typedef const char* (*config_fn_t)(void);
-
-#ifdef SHIB_APACHE_13
-
-// SHIB Module commands
-
-static command_rec shire_cmds[] = {
-  {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
-   RSRC_CONF, TAKE1, "Shibboleth installation directory"},
-  {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
-   RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
-  {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
-   RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
-
-  {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
-   (void *) XtOffsetOf (shib_server_config, szScheme),
-   RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
-
-  {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
-   OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
-
-  {"ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
-   OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
-
-  {"ShibDisable", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bOff),
-   OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
-  {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
-   (void *) XtOffsetOf (shib_dir_config, szApplicationId),
-   OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
-  {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
-   OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
-  {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bRequireSession),
-   OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
-  {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
-   (void *) XtOffsetOf (shib_dir_config, szRequireWith),
-   OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
-  {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
-   OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
-  {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
-   (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
-   OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
-  {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
-   (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
-   OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
-  {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bRequireAll),
-   OR_AUTHCFG, FLAG, "All require directives must match"},
-  {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
-   OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
-  {"ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bCompatWith24),
-   OR_AUTHCFG, FLAG, "Support Apache 2.4-style require rules"},
-  {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
-   OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
-  {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
-   OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
-  {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
-   (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
-   OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
-
-  {nullptr}
-};
-
-extern "C"{
-handler_rec shib_handlers[] = {
-  { "shib-handler", shib_handler },
-  { nullptr }
-};
-
-module MODULE_VAR_EXPORT mod_shib = {
-    STANDARD_MODULE_STUFF,
-    nullptr,                        /* initializer */
-    create_shib_dir_config,	/* dir config creater */
-    merge_shib_dir_config,	/* dir merger --- default is to override */
-    create_shib_server_config, /* server config */
-    merge_shib_server_config,   /* merge server config */
-    shire_cmds,			/* command table */
-    shib_handlers,		/* handlers */
-    nullptr,			/* filename translation */
-    shib_check_user,		/* check_user_id */
-    shib_auth_checker,		/* check auth */
-    nullptr,			/* check access */
-    nullptr,			/* type_checker */
-    shib_fixups,		/* fixups */
-    nullptr,			/* logger */
-    nullptr,			/* header parser */
-    shib_child_init,		/* child_init */
-    shib_child_exit,		/* child_exit */
-    shib_post_read		/* post read-request */
-};
-
-#else
-
-#ifdef SHIB_APACHE_24
-extern "C" const authz_provider shib_authz_shibboleth_provider = { &shib_shibboleth_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_validuser_provider = { &shib_validuser_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_session_provider = { &shib_session_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_user_provider = { &shib_user_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_ext_user_provider = { &shib_ext_user_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_acclass_provider = { &shib_acclass_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_acdecl_provider = { &shib_acdecl_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_attr_provider = { &shib_attr_check_authz, nullptr };
-extern "C" const authz_provider shib_authz_plugin_provider = { &shib_plugin_check_authz, nullptr };
-#endif
-
-extern "C" void shib_register_hooks (apr_pool_t *p)
-{
-#ifdef SHIB_DEFERRED_HEADERS
-    ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
-    ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
-    ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
-    ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
-    ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
-#endif
-    ap_hook_post_config(shib_post_config, nullptr, nullptr, APR_HOOK_MIDDLE);
-    ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
-    const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
-#ifdef SHIB_APACHE_24
-    if (prereq && *prereq) {
-        const char* const authnPre[] = { prereq, nullptr };
-        ap_hook_check_authn(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
-    }
-    else {
-        ap_hook_check_authn(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
-    }
-    ap_hook_check_authz(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_URI);
-#else
-    if (prereq && *prereq) {
-        const char* const authnPre[] = { prereq, nullptr };
-        ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
-    }
-    else {
-        ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
-    }
-    ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
-#endif
-    ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
-    ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
-
-#ifdef SHIB_APACHE_24
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shibboleth", AUTHZ_PROVIDER_VERSION, &shib_authz_shibboleth_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "valid-user", AUTHZ_PROVIDER_VERSION, &shib_authz_validuser_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-session", AUTHZ_PROVIDER_VERSION, &shib_authz_session_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "user", AUTHZ_PROVIDER_VERSION, &shib_authz_user_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-user", AUTHZ_PROVIDER_VERSION, &shib_authz_ext_user_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextClassRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acclass_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextDeclRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acdecl_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-attr", AUTHZ_PROVIDER_VERSION, &shib_authz_attr_provider, AP_AUTH_INTERNAL_PER_CONF);
-    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-plugin", AUTHZ_PROVIDER_VERSION, &shib_authz_plugin_provider, AP_AUTH_INTERNAL_PER_CONF);
-#endif
-}
-
-// SHIB Module commands
-
-extern "C" {
-static command_rec shib_cmds[] = {
-    AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
-        RSRC_CONF, "Shibboleth installation directory"),
-    AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
-        RSRC_CONF, "Path to shibboleth2.xml config file"),
-    AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
-        RSRC_CONF, "Paths of XML schema catalogs"),
-    AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
-        RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
-
-    AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
-        (void *) offsetof (shib_server_config, szScheme),
-        RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
-
-    AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
-        OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
-
-    AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bOff),
-        OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
-    AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
-        (void *) offsetof (shib_dir_config, szApplicationId),
-        OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
-    AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bBasicHijack),
-        OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
-    AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bRequireSession),
-        OR_AUTHCFG, "Initiates a new session if one does not exist"),
-    AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
-        (void *) offsetof (shib_dir_config, szRequireWith),
-        OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
-    AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bExportAssertion),
-        OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
-    AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
-        (void *) offsetof (shib_dir_config, szRedirectToSSL),
-        OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
-#ifdef SHIB_APACHE_24
-    AP_INIT_FLAG("ShibRequestMapperAuthz", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bRequestMapperAuthz),
-        OR_AUTHCFG, "Support access control via shibboleth2.xml / RequestMapper"),
-    AP_INIT_FLAG("ShibCompatValidUser", (config_fn_t)shib_set_server_flag_slot,
-        (void *) offsetof (shib_server_config, bCompatValidUser),
-        RSRC_CONF, "Handle 'require valid-user' in mod_authz_user-compatible fashion (requiring username)"),
-#else
-    AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
-        (void *) offsetof (shib_dir_config, szAuthGrpFile),
-        OR_AUTHCFG, "Text file containing group names and member user IDs"),
-    AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
-        OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
-    AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bRequireAll),
-        OR_AUTHCFG, "All require directives must match"),
-    AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bAuthoritative),
-        OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
-    AP_INIT_FLAG("ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bCompatWith24),
-        OR_AUTHCFG, "Support Apache 2.4-style require rules"),
-#endif
-    AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bUseEnvVars),
-        OR_AUTHCFG, "Export attributes using environment variables (default)"),
-    AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bUseHeaders),
-        OR_AUTHCFG, "Export attributes using custom HTTP headers"),
-    AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
-        (void *) offsetof (shib_dir_config, bExpireRedirects),
-        OR_AUTHCFG, "Expire SP-generated redirects"),
-
-    {nullptr}
-};
-
-module AP_MODULE_DECLARE_DATA mod_shib = {
-    STANDARD20_MODULE_STUFF,
-    create_shib_dir_config,     /* create dir config */
-    merge_shib_dir_config,      /* merge dir config --- default is to override */
-    create_shib_server_config,  /* create server config */
-    merge_shib_server_config,   /* merge server config */
-    shib_cmds,                  /* command table */
-    shib_register_hooks         /* register hooks */
-};
-
-#endif
-
-}
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
+ *
+ * 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.
+ */
+
+/**
+ * mod_shib.cpp
+ *
+ * Apache module implementation.
+ */
+
+#define SHIBSP_LITE
+
+#ifdef SOLARIS2
+#undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
+#endif
+
+#ifdef WIN32
+# define _CRT_NONSTDC_NO_DEPRECATE 1
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+
+#include <shibsp/exceptions.h>
+#include <shibsp/AbstractSPRequest.h>
+#include <shibsp/AccessControl.h>
+#include <shibsp/GSSRequest.h>
+#include <shibsp/RequestMapper.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.h>
+#include <shibsp/SessionCache.h>
+#include <shibsp/attribute/Attribute.h>
+
+#include <xercesc/util/XMLUniDefs.hpp>
+#include <xercesc/util/regx/RegularExpression.hpp>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/ParserPool.h>
+#include <xmltooling/util/Threads.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
+
+#ifdef WIN32
+# include <winsock2.h>
+# include <ws2tcpip.h>
+#endif
+
+#undef _XPG4_2
+
+#include <set>
+#include <memory>
+#include <fstream>
+#include <stdexcept>
+#include <boost/lexical_cast.hpp>
+
+// Apache specific header files
+#include <httpd.h>
+#include <http_config.h>
+#include <http_protocol.h>
+#include <http_main.h>
+#define CORE_PRIVATE
+#include <http_core.h>
+#include <http_log.h>
+#include <http_request.h>
+
+#ifndef SHIB_APACHE_13
+#include <apr_buckets.h>
+#include <apr_strings.h>
+#include <apr_pools.h>
+#endif
+
+#ifdef SHIB_APACHE_24
+#include <mod_auth.h>
+#endif
+
+#include <cstddef>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>		// for getpid()
+#endif
+
+using namespace shibsp;
+using namespace xmltooling;
+using namespace boost;
+using namespace std;
+using xercesc::RegularExpression;
+using xercesc::XMLException;
+
+#ifdef APLOG_USE_MODULE
+    extern "C" module AP_MODULE_DECLARE_DATA mod_shib;
+    static int* const aplog_module_index = &(mod_shib.module_index);
+#else
+    extern "C" module MODULE_VAR_EXPORT mod_shib;
+#endif
+
+namespace {
+    char* g_szSHIBConfig = nullptr;
+    char* g_szSchemaDir = nullptr;
+    char* g_szPrefix = nullptr;
+    SPConfig* g_Config = nullptr;
+    string g_unsetHeaderValue,g_spoofKey;
+    bool g_checkSpoofing = true;
+    bool g_catchAll = false;
+#ifndef SHIB_APACHE_13
+    char* g_szGSSContextKey = "mod_auth_gssapi:gss_ctx";
+#endif
+    static const char* g_UserDataKey = "urn:mace:shibboleth:Apache:shib_check_user";
+}
+
+/* Apache 2.2.x headers must be accumulated and set in the output filter.
+   Apache 2.0.49+ supports the filter method.
+   Apache 1.3.x and lesser 2.0.x must write the headers directly. */
+
+#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
+#define SHIB_DEFERRED_HEADERS
+#endif
+
+/********************************************************************************/
+// Basic Apache Configuration code.
+//
+
+// per-server module configuration structure
+struct shib_server_config
+{
+    char* szScheme;
+    int bCompatValidUser;
+};
+
+// creates the per-server configuration
+extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
+{
+    shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
+    sc->szScheme = nullptr;
+    sc->bCompatValidUser = -1;
+    return sc;
+}
+
+// overrides server configuration in virtual servers
+extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
+{
+    shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
+    shib_server_config* parent=(shib_server_config*)base;
+    shib_server_config* child=(shib_server_config*)sub;
+
+    if (child->szScheme)
+        sc->szScheme=ap_pstrdup(p,child->szScheme);
+    else if (parent->szScheme)
+        sc->szScheme=ap_pstrdup(p,parent->szScheme);
+    else
+        sc->szScheme=nullptr;
+
+    sc->bCompatValidUser = ((child->bCompatValidUser==-1) ? parent->bCompatValidUser : child->bCompatValidUser);
+
+    return sc;
+}
+
+// per-dir module configuration structure
+struct shib_dir_config
+{
+    SH_AP_TABLE* tSettings; // generic table of extensible settings
+
+    // RM Configuration
+#ifdef SHIB_APACHE_24
+    int bRequestMapperAuthz;// support RequestMapper AccessControl plugins
+#else
+    char* szAuthGrpFile;    // Auth GroupFile name
+	char* szAccessControl;	// path to "external" AccessControl plugin file
+    int bRequireAll;        // all "known" require directives must match, otherwise OR logic
+    int bAuthoritative;     // allow htaccess plugin to DECLINE when authz fails
+    int bCompatWith24;      // support 2.4-reserved require logic for compatibility
+#endif
+
+    // Content Configuration
+    char* szApplicationId;  // Shib applicationId value
+    char* szRequireWith;    // require a session using a specific initiator?
+    char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
+    int bOff;               // flat-out disable all Shib processing
+    int bBasicHijack;       // activate for AuthType Basic?
+    int bRequireSession;    // require a session?
+    int bExportAssertion;   // export SAML assertion to the environment?
+    int bUseEnvVars;        // use environment?
+    int bUseHeaders;        // use headers?
+    int bExpireRedirects;   // expire redirects?
+};
+
+// creates per-directory config structure
+extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
+{
+    shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
+    dc->tSettings = nullptr;
+#ifdef SHIB_APACHE_24
+    dc->bRequestMapperAuthz = -1;
+#else
+    dc->szAuthGrpFile = nullptr;
+	dc->szAccessControl = nullptr;
+    dc->bRequireAll = -1;
+    dc->bAuthoritative = -1;
+    dc->bCompatWith24 = -1;
+#endif
+    dc->szApplicationId = nullptr;
+    dc->szRequireWith = nullptr;
+    dc->szRedirectToSSL = nullptr;
+    dc->bOff = -1;
+    dc->bBasicHijack = -1;
+    dc->bRequireSession = -1;
+    dc->bExportAssertion = -1;
+    dc->bUseEnvVars = -1;
+    dc->bUseHeaders = -1;
+    dc->bExpireRedirects = -1;
+    return dc;
+}
+
+// overrides server configuration in directories
+extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
+{
+    shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
+    shib_dir_config* parent=(shib_dir_config*)base;
+    shib_dir_config* child=(shib_dir_config*)sub;
+
+    // The child supersedes any matching table settings in the parent.
+    dc->tSettings = nullptr;
+    if (parent->tSettings)
+        dc->tSettings = ap_copy_table(p, parent->tSettings);
+    if (child->tSettings) {
+        if (dc->tSettings)
+            ap_overlap_tables(dc->tSettings, child->tSettings, AP_OVERLAP_TABLES_SET);
+        else
+            dc->tSettings = ap_copy_table(p, child->tSettings);
+    }
+
+#ifdef SHIB_APACHE_24
+    dc->bRequestMapperAuthz = ((child->bRequestMapperAuthz==-1) ? parent->bRequestMapperAuthz : child->bRequestMapperAuthz);
+#else
+    if (child->szAuthGrpFile)
+        dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
+    else if (parent->szAuthGrpFile)
+        dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
+    else
+        dc->szAuthGrpFile=nullptr;
+
+	if (child->szAccessControl)
+        dc->szAccessControl=ap_pstrdup(p,child->szAccessControl);
+    else if (parent->szAccessControl)
+        dc->szAccessControl=ap_pstrdup(p,parent->szAccessControl);
+    else
+        dc->szAccessControl=nullptr;
+#endif
+
+    if (child->szApplicationId)
+        dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
+    else if (parent->szApplicationId)
+        dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
+    else
+        dc->szApplicationId=nullptr;
+
+    if (child->szRequireWith)
+        dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
+    else if (parent->szRequireWith)
+        dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
+    else
+        dc->szRequireWith=nullptr;
+
+    if (child->szRedirectToSSL)
+        dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
+    else if (parent->szRedirectToSSL)
+        dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
+    else
+        dc->szRedirectToSSL=nullptr;
+
+    dc->bOff = ((child->bOff==-1) ? parent->bOff : child->bOff);
+    dc->bBasicHijack = ((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
+    dc->bRequireSession = ((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
+    dc->bExportAssertion = ((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
+#ifndef SHIB_APACHE_24
+    dc->bRequireAll = ((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
+    dc->bAuthoritative = ((child->bAuthoritative==-1) ? parent->bAuthoritative : child->bAuthoritative);
+    dc->bCompatWith24 = ((child->bCompatWith24==-1) ? parent->bCompatWith24 : child->bCompatWith24);
+#endif
+    dc->bUseEnvVars = ((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
+    dc->bUseHeaders = ((child->bUseHeaders==-1) ? parent->bUseHeaders : child->bUseHeaders);
+    dc->bExpireRedirects = ((child->bExpireRedirects==-1) ? parent->bExpireRedirects : child->bExpireRedirects);
+    return dc;
+}
+
+class ShibTargetApache; // forward decl
+
+// per-request module structure
+struct shib_request_config
+{
+    SH_AP_TABLE* env;        // environment vars
+#ifdef SHIB_DEFERRED_HEADERS
+    SH_AP_TABLE* hdr_out;    // headers to browser
+#endif
+#ifndef SHIB_APACHE_13
+    ShibTargetApache* sta;  // SP per-request structure wrapped around Apache's request
+#endif
+};
+
+// create or return a request record
+static shib_request_config* get_request_config(request_rec *r)
+{
+    shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+    if (rc) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config called redundantly");
+    }
+    else {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "get_request_config created per-request structure");
+        rc = (shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
+        memset(rc, 0, sizeof(shib_request_config));
+        ap_set_module_config(r->request_config, &mod_shib, rc);
+    }
+    return rc;
+}
+
+class ShibTargetApache : public AbstractSPRequest
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+    , public GSSRequest
+#endif
+{
+  mutable string m_body;
+  mutable bool m_gotBody,m_firsttime;
+  mutable vector<string> m_certs;
+  set<string> m_allhttp;
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+  mutable gss_name_t m_gssname;
+#endif
+
+public:
+  bool m_handler;
+  request_rec* m_req;
+  shib_dir_config* m_dc;
+  shib_server_config* m_sc;
+  shib_request_config* m_rc;
+
+  ShibTargetApache(request_rec* req) : AbstractSPRequest(SHIBSP_LOGCAT ".Apache"),
+        m_gotBody(false),m_firsttime(true),
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+        m_gssname(GSS_C_NO_NAME),
+#endif
+        m_handler(false), m_req(req), m_dc(nullptr), m_sc(nullptr), m_rc(nullptr) {
+  }
+  virtual ~ShibTargetApache() {
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+    if (m_gssname != GSS_C_NO_NAME) {
+        OM_uint32 minor;
+        gss_release_name(&minor, &m_gssname);
+    }
+#endif
+  }
+
+  bool isInitialized() const {
+      return (m_sc != nullptr);
+  }
+
+  bool init(bool handler, bool check_user) {
+    m_handler = handler;
+    if (m_sc)
+        return !check_user; // only initialize once
+    m_sc = (shib_server_config*)ap_get_module_config(m_req->server->module_config, &mod_shib);
+    m_dc = (shib_dir_config*)ap_get_module_config(m_req->per_dir_config, &mod_shib);
+    m_rc = (shib_request_config*)ap_get_module_config(m_req->request_config, &mod_shib);
+
+    setRequestURI(m_req->unparsed_uri);
+
+    if (check_user && m_dc->bUseHeaders == 1) {
+        // Try and see if this request was already processed, to skip spoof checking.
+        if (!ap_is_initial_req(m_req)) {
+            m_firsttime = false;
+        }
+        else if (!g_spoofKey.empty()) {
+            const char* hdr = ap_table_get(m_req->headers_in, "Shib-Spoof-Check");
+            if (hdr && g_spoofKey == hdr)
+                m_firsttime = false;
+        }
+        if (!m_firsttime)
+            log(SPDebug, "shib_check_user running more than once");
+    }
+    return true;
+  }
+
+  const char* getScheme() const {
+    return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
+  }
+  bool isSecure() const {
+      return HTTPRequest::isSecure();
+  }
+  const char* getHostname() const {
+#ifdef SHIB_APACHE_24
+      return ap_get_server_name_for_url(m_req);
+#else
+      return ap_get_server_name(m_req);
+#endif
+  }
+  int getPort() const {
+    return ap_get_server_port(m_req);
+  }
+  const char* getMethod() const {
+    return m_req->method;
+  }
+  string getContentType() const {
+    const char* type = ap_table_get(m_req->headers_in, "Content-Type");
+    return type ? type : "";
+  }
+  long getContentLength() const {
+      // Apache won't expose content length until the body's read.
+      if (!m_gotBody) {
+          getRequestBody();
+      }
+      return m_body.length();
+  }
+  string getRemoteAddr() const {
+    string ret = AbstractSPRequest::getRemoteAddr();
+    if (!ret.empty())
+        return ret;
+#ifdef SHIB_APACHE_24
+    return m_req->useragent_ip;
+#else
+    return m_req->connection->remote_ip;
+#endif
+  }
+  void log(SPLogLevel level, const string& msg) const {
+    AbstractSPRequest::log(level,msg);
+    ap_log_rerror(
+        APLOG_MARK,
+        (level == SPDebug ? APLOG_DEBUG :
+        (level == SPInfo ? APLOG_INFO :
+        (level == SPWarn ? APLOG_WARNING :
+        (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
+        SH_AP_R(m_req),
+        "%s",
+        msg.c_str()
+        );
+  }
+  const char* getQueryString() const { return m_req->args; }
+  const char* getRequestBody() const {
+    if (m_gotBody || m_req->method_number==M_GET)
+        return m_body.c_str();
+#ifdef SHIB_APACHE_13
+    // Read the posted data
+    if (ap_setup_client_block(m_req, REQUEST_CHUNKED_DECHUNK) != OK) {
+        m_gotBody=true;
+        log(SPError, "Apache function (setup_client_block) failed while reading request body.");
+        return m_body.c_str();
+    }
+    if (!ap_should_client_block(m_req)) {
+        m_gotBody=true;
+        log(SPError, "Apache function (should_client_block) failed while reading request body.");
+        return m_body.c_str();
+    }
+    if (m_req->remaining > 1024*1024)
+        throw opensaml::SecurityPolicyException("Blocked request body larger than 1M size limit.");
+    m_gotBody=true;
+    int len;
+    char buff[HUGE_STRING_LEN];
+    ap_hard_timeout("[mod_shib] getRequestBody", m_req);
+    while ((len=ap_get_client_block(m_req, buff, sizeof(buff))) > 0) {
+      ap_reset_timeout(m_req);
+      m_body.append(buff, len);
+    }
+    ap_kill_timeout(m_req);
+#else
+    const char *data;
+    apr_size_t len;
+    int seen_eos = 0;
+    apr_bucket_brigade* bb = apr_brigade_create(m_req->pool, m_req->connection->bucket_alloc);
+    do {
+        apr_bucket *bucket;
+        apr_status_t rv = ap_get_brigade(m_req->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN);
+        if (rv != APR_SUCCESS) {
+            log(SPError, "Apache function (ap_get_brigade) failed while reading request body.");
+            break;
+        }
+
+        for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb); bucket = APR_BUCKET_NEXT(bucket)) {
+            if (APR_BUCKET_IS_EOS(bucket)) {
+                seen_eos = 1;
+                break;
+            }
+
+            /* We can't do much with this. */
+            if (APR_BUCKET_IS_FLUSH(bucket))
+                continue;
+
+            /* read */
+            apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
+            if (len > 0)
+                m_body.append(data, len);
+        }
+        apr_brigade_cleanup(bb);
+    } while (!seen_eos);
+    apr_brigade_destroy(bb);
+    m_gotBody=true;
+#endif
+    return m_body.c_str();
+  }
+  const char* getParameter(const char* name) const {
+      return AbstractSPRequest::getParameter(name);
+  }
+  vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const {
+      return AbstractSPRequest::getParameters(name, values);
+  }
+  void clearHeader(const char* rawname, const char* cginame) {
+    if (m_dc->bUseHeaders == 1) {
+       // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
+        if (g_checkSpoofing && m_firsttime) {
+            if (m_allhttp.empty()) {
+                // First time, so populate set with "CGI" versions of client-supplied headers.
+#ifdef SHIB_APACHE_13
+                array_header *hdrs_arr = ap_table_elts(m_req->headers_in);
+                table_entry *hdrs = (table_entry *) hdrs_arr->elts;
+#else
+                const apr_array_header_t *hdrs_arr = apr_table_elts(m_req->headers_in);
+                const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
+#endif
+                for (int i = 0; i < hdrs_arr->nelts; ++i) {
+                    if (!hdrs[i].key)
+                        continue;
+                    string cgiversion("HTTP_");
+                    const char* pch = hdrs[i].key;
+                    while (*pch) {
+                        cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
+                        pch++;
+                    }
+                    m_allhttp.insert(cgiversion);
+                }
+            }
+
+            if (m_allhttp.count(cginame) > 0)
+                throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
+        }
+        ap_table_unset(m_req->headers_in, rawname);
+        ap_table_set(m_req->headers_in, rawname, g_unsetHeaderValue.c_str());
+    }
+  }
+  void setHeader(const char* name, const char* value) {
+    if (m_dc->bUseEnvVars != 0) {
+       if (!m_rc) {
+          // this happens on subrequests
+          // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
+          m_rc = get_request_config(m_req);
+       }
+       if (!m_rc->env)
+           m_rc->env = ap_make_table(m_req->pool, 10);
+       // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
+       ap_table_set(m_rc->env, name, value ? value : "");
+    }
+    if (m_dc->bUseHeaders == 1)
+       ap_table_set(m_req->headers_in, name, value);
+  }
+  string getHeader(const char* name) const {
+    const char* hdr = ap_table_get(m_req->headers_in, name);
+    return string(hdr ? hdr : "");
+  }
+  string getSecureHeader(const char* name) const {
+    if (m_dc->bUseEnvVars != 0) {
+       const char *hdr;
+       if (m_rc && m_rc->env)
+           hdr = ap_table_get(m_rc->env, name);
+       else
+           hdr = nullptr;
+       return string(hdr ? hdr : "");
+    }
+    return getHeader(name);
+  }
+  void setRemoteUser(const char* user) {
+      SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : nullptr;
+      if (m_dc->bUseHeaders == 1) {
+          if (user) {
+              ap_table_set(m_req->headers_in, "REMOTE_USER", user);
+          }
+          else {
+              ap_table_unset(m_req->headers_in, "REMOTE_USER");
+              ap_table_set(m_req->headers_in, "REMOTE_USER", g_unsetHeaderValue.c_str());
+          }
+      }
+  }
+  string getRemoteUser() const {
+    return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
+  }
+  void setAuthType(const char* authtype) {
+      if (authtype && m_dc->bBasicHijack == 1)
+          authtype = "Basic";
+      SH_AP_AUTH_TYPE(m_req) = authtype ? ap_pstrdup(m_req->pool, authtype) : nullptr;
+  }
+  string getAuthType() const {
+    return string(SH_AP_AUTH_TYPE(m_req) ? SH_AP_AUTH_TYPE(m_req) : "");
+  }
+  void setContentType(const char* type) {
+      m_req->content_type = ap_psprintf(m_req->pool, "%s", type);
+  }
+  void setResponseHeader(const char* name, const char* value) {
+    HTTPResponse::setResponseHeader(name, value);
+    if (name) {
+#ifdef SHIB_DEFERRED_HEADERS
+        if (!m_rc) {
+            // this happens on subrequests
+            m_rc = get_request_config(m_req);
+        }
+        if (m_handler) {
+            if (!m_rc->hdr_out) {
+                m_rc->hdr_out = ap_make_table(m_req->pool, 5);
+            }
+            ap_table_add(m_rc->hdr_out, name, value);
+        }
+        else
+#endif
+            ap_table_add(m_req->err_headers_out, name, value);
+    }
+  }
+  long sendResponse(istream& in, long status) {
+    if (status != XMLTOOLING_HTTP_STATUS_OK)
+        m_req->status = status;
+    ap_send_http_header(m_req);
+    char buf[1024];
+    while (in) {
+        in.read(buf,1024);
+        ap_rwrite(buf,in.gcount(),m_req);
+    }
+#if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22) || defined(SHIB_APACHE_24))
+    if (status != XMLTOOLING_HTTP_STATUS_OK && status != XMLTOOLING_HTTP_STATUS_ERROR)
+        return status;
+#endif
+    return DONE;
+  }
+  long sendRedirect(const char* url) {
+    HTTPResponse::sendRedirect(url);
+    ap_table_set(m_req->headers_out, "Location", url);
+    if (m_dc->bExpireRedirects != 0) {
+        ap_table_set(m_req->err_headers_out, "Expires", "Wed, 01 Jan 1997 12:00:00 GMT");
+        ap_table_set(m_req->err_headers_out, "Cache-Control", "private,no-store,no-cache,max-age=0");
+    }
+    return REDIRECT;
+  }
+  const vector<string>& getClientCertificates() const {
+      if (m_certs.empty()) {
+          const char* cert = ap_table_get(m_req->subprocess_env, "SSL_CLIENT_CERT");
+          if (cert)
+              m_certs.push_back(cert);
+          int i = 0;
+          do {
+              cert = ap_table_get(m_req->subprocess_env, ap_psprintf(m_req->pool, "SSL_CLIENT_CERT_CHAIN_%d", i++));
+              if (cert)
+                  m_certs.push_back(cert);
+          } while (cert);
+      }
+      return m_certs;
+  }
+  long returnDecline(void) { return DECLINED; }
+  long returnOK(void) { return OK; }
+#if defined(SHIBSP_HAVE_GSSAPI) && !defined(SHIB_APACHE_13)
+  gss_ctx_id_t getGSSContext() const {
+    gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
+    apr_pool_userdata_get((void**)&ctx, g_szGSSContextKey, m_req->pool);
+    return ctx;
+  }
+  gss_name_t getGSSName() const {
+      if (m_gssname == GSS_C_NO_NAME) {
+          gss_ctx_id_t ctx = getGSSContext();
+          if (ctx != GSS_C_NO_CONTEXT) {
+              OM_uint32 minor;
+              OM_uint32 major = gss_inquire_context(&minor, ctx, &m_gssname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
+              if (major != GSS_S_COMPLETE)
+                  m_gssname = GSS_C_NO_NAME;
+          }
+      }
+      return m_gssname;
+  }
+  #endif
+};
+
+/********************************************************************************/
+// Apache hooks
+
+#ifndef SHIB_APACHE_13
+extern "C" apr_status_t shib_request_cleanup(void* rc)
+{
+    if (rc && reinterpret_cast<shib_request_config*>(rc)->sta) {
+        delete reinterpret_cast<ShibTargetApache*>(reinterpret_cast<shib_request_config*>(rc)->sta);
+        reinterpret_cast<shib_request_config*>(rc)->sta = nullptr;
+    }
+    return APR_SUCCESS;
+}
+#endif
+
+// Initial look at a request - create the per-request structure if need be
+static int shib_post_read(request_rec *r)
+{
+    shib_request_config* rc = get_request_config(r);
+#ifdef SHIB_APACHE_24
+    if (!rc->sta) {
+        rc->sta = new ShibTargetApache(r);
+        apr_pool_cleanup_register(r->pool, rc, shib_request_cleanup, apr_pool_cleanup_null);
+    }
+#endif
+    return DECLINED;
+}
+
+// Performs authentication and enforce session requirements.
+// Also does header/env export from session, and will dispatch
+// SP handler requests if it detects a handler URL.
+extern "C" int shib_check_user(request_rec* r)
+{
+    // Short-circuit entirely?
+    if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
+        return DECLINED;
+
+    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user entered in pid (%d)", (int)getpid());
+
+    string threadid("[");
+    threadid += lexical_cast<string>(getpid()) + "] shib_check_user";
+    xmltooling::NDC ndc(threadid.c_str());
+
+    try {
+#ifndef SHIB_APACHE_24
+        ShibTargetApache sta(r);
+        ShibTargetApache* psta = &sta;
+#else
+        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        if (!rc || !rc->sta) {
+            ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user found no per-request structure");
+            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
+            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        }
+        ShibTargetApache* psta = rc->sta;
+#endif
+        if (!psta->init(false, true)) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user unable to initialize SP request object");
+            return SERVER_ERROR;
+        }
+
+        // Check user authentication and export information, then set the handler bypass
+        pair<bool,long> res = psta->getServiceProvider().doAuthentication(*psta, true);
+        apr_pool_userdata_setn((const void*)42,g_UserDataKey,nullptr,r->pool);
+        // If directed, install a spoof key to recognize when we've already cleared headers.
+        if (!g_spoofKey.empty() && (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bUseHeaders == 1))
+            ap_table_set(r->headers_in, "Shib-Spoof-Check", g_spoofKey.c_str());
+        if (res.first) {
+#ifdef SHIB_APACHE_24
+            // This is insane, but Apache's internal request.c logic insists that an auth module
+            // returning OK MUST set r->user to avoid a failure. But they check for NULL and not
+            // for an empty string. If this turns out to cause trouble, there's no solution except
+            // to set a dummy ID any time it's not set.
+            if (res.second == OK && !r->user)
+                r->user = "";
+#endif
+            return res.second;
+        }
+
+        // user auth was okay -- export the session data now
+        res = psta->getServiceProvider().doExport(*psta);
+        if (res.first) {
+#ifdef SHIB_APACHE_24
+            // See above for explanation of this hack.
+            if (res.second == OK && !r->user)
+                r->user = "";
+#endif
+            return res.second;
+        }
+
+#ifdef SHIB_APACHE_24
+        // See above for explanation of this hack.
+        if (!r->user)
+            r->user = "";
+#endif
+        return OK;
+    }
+    catch (std::exception& e) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
+        return SERVER_ERROR;
+    }
+    catch (...) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an unknown exception!");
+        if (g_catchAll)
+            return SERVER_ERROR;
+        throw;
+    }
+}
+
+// Runs SP handler requests when invoked directly.
+extern "C" int shib_handler(request_rec* r)
+{
+    // Short-circuit entirely?
+    if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff == 1)
+        return DECLINED;
+
+    string threadid("[");
+    threadid += lexical_cast<string>(getpid()) + "] shib_handler";
+    xmltooling::NDC ndc(threadid.c_str());
+
+#ifndef SHIB_APACHE_13
+    // With 2.x, this handler always runs, though last.
+    // We check if shib_check_user ran, because it will detect a handler request
+    // and dispatch it directly.
+    void* data;
+    apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
+    if (data==(const void*)42) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler skipped since check_user ran");
+        return DECLINED;
+    }
+#endif
+
+    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler entered in pid (%d): %s", (int)getpid(), r->handler);
+
+    try {
+#ifndef SHIB_APACHE_24
+        ShibTargetApache sta(r);
+        ShibTargetApache* psta = &sta;
+#else
+        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        if (!rc || !rc->sta) {
+            ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_handler found no per-request structure");
+            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
+            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        }
+        ShibTargetApache* psta = rc->sta;
+#endif
+        if (!psta->init(true, false)) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler unable to initialize SP request object");
+            return SERVER_ERROR;
+        }
+
+        pair<bool,long> res = psta->getServiceProvider().doHandler(*psta);
+        if (res.first) return res.second;
+
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not handle the request");
+        return SERVER_ERROR;
+    }
+    catch (std::exception& e) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
+        return SERVER_ERROR;
+    }
+    catch (...) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an unknown exception!");
+        if (g_catchAll)
+          return SERVER_ERROR;
+        throw;
+    }
+}
+
+// This performs authorization functions to limit access.
+// On all versions, this runs any RequestMap-attached plugins.
+// For pre-2.4 versions, the RequestMap will always find an htAccess plugin
+// that runs code to parse and enforce Apache Require rules.
+// On 2.4, we have to short-circuit that and let Apache run callbacks
+// for each Require rule we handle.
+extern "C" int shib_auth_checker(request_rec* r)
+{
+    // Short-circuit entirely?
+    shib_dir_config* dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
+    if (dc->bOff == 1
+#ifdef SHIB_APACHE_24
+        || dc->bRequestMapperAuthz == 0     // this allows for bypass of the full auth_checker hook if only htaccess is used
+#endif
+        ) {
+        return DECLINED;
+    }
+
+    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker entered in pid (%d)", (int)getpid());
+
+    string threadid("[");
+    threadid += lexical_cast<string>(getpid()) + "] shib_auth_checker";
+    xmltooling::NDC ndc(threadid.c_str());
+
+    try {
+#ifndef SHIB_APACHE_24
+        ShibTargetApache sta(r);
+        ShibTargetApache* psta = &sta;
+#else
+        shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        if (!rc || !rc->sta) {
+            ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker found no per-request structure");
+            shib_post_read(r);  // ensures objects are created if post_read hook didn't run
+            rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+        }
+        ShibTargetApache* psta = rc->sta;
+#endif
+        if (!psta->init(false, false)) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker unable to initialize SP request object");
+            return SERVER_ERROR;
+        }
+
+        pair<bool,long> res = psta->getServiceProvider().doAuthorization(*psta);
+        if (res.first) return res.second;
+
+        // The SP method should always return true, so if we get this far, something unusual happened.
+        // Just let Apache (or some other module) decide what to do.
+        return DECLINED;
+    }
+    catch (std::exception& e) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
+        return SERVER_ERROR;
+    }
+    catch (...) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an unknown exception!");
+        if (g_catchAll)
+          return SERVER_ERROR;
+        throw;
+    }
+}
+
+// Overlays environment variables on top of subprocess table.
+extern "C" int shib_fixups(request_rec* r)
+{
+    shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
+    if (dc->bOff==1 || dc->bUseEnvVars==0)
+        return DECLINED;
+
+    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups entered in pid (%d)", (int)getpid());
+
+    shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+    if (rc==nullptr || rc->env==nullptr || ap_is_empty_table(rc->env))
+        return DECLINED;
+
+    ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_fixups adding %d vars", ap_table_elts(rc->env)->nelts);
+    r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
+
+    return OK;
+}
+
+
+// Access control plugin that enforces pre-2.4 htaccess rules.
+// Post-2.4, we have to register individual methods to respond
+// to each require rule we want to handle, and have those call
+// into these methods directly.
+class htAccessControl : virtual public AccessControl
+{
+public:
+    htAccessControl() {}
+    ~htAccessControl() {}
+    Lockable* lock() {return this;}
+    void unlock() {}
+    aclresult_t authorized(const SPRequest& request, const Session* session) const;
+
+    aclresult_t doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const;
+    aclresult_t doUser(const ShibTargetApache& sta, const char* params) const;
+#ifndef SHIB_APACHE_24
+    aclresult_t doGroup(const ShibTargetApache& sta, const char* params) const;
+#endif
+    aclresult_t doAuthnContext(const ShibTargetApache& sta, const char* acRef, const char* params) const;
+    aclresult_t doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const;
+
+private:
+    bool checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const;
+};
+
+AccessControl* htAccessFactory(const xercesc::DOMElement* const & e)
+{
+    return new htAccessControl();
+}
+
+AccessControl::aclresult_t htAccessControl::doAccessControl(const ShibTargetApache& sta, const Session* session, const char* plugin) const
+{
+	aclresult_t result = shib_acl_false;
+	try {
+        ifstream aclfile(plugin);
+        if (!aclfile)
+            throw ConfigurationException("Unable to open access control file ($1).", params(1, plugin));
+        xercesc::DOMDocument* acldoc = XMLToolingConfig::getConfig().getParser().parse(aclfile);
+		XercesJanitor<xercesc::DOMDocument> docjanitor(acldoc);
+		static XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
+        string t(XMLHelper::getAttrString(acldoc ? acldoc->getDocumentElement() : nullptr, nullptr, _type));
+        if (t.empty())
+            throw ConfigurationException("Missing type attribute in AccessControl plugin configuration.");
+        scoped_ptr<AccessControl> aclplugin(SPConfig::getConfig().AccessControlManager.newPlugin(t.c_str(), acldoc->getDocumentElement()));
+		Locker acllock(aclplugin.get());
+		result = aclplugin->authorized(sta, session);
+	}
+	catch (std::exception& ex) {
+		sta.log(SPRequest::SPError, ex.what());
+	}
+    return result;
+}
+
+AccessControl::aclresult_t htAccessControl::doUser(const ShibTargetApache& sta, const char* params) const
+{
+    bool regexp = false;
+    bool negated = false;
+    while (*params) {
+        const char* w = ap_getword_conf(sta.m_req->pool, &params);
+        if (*w == '~') {
+            regexp = true;
+            continue;
+        }
+        else if (*w == '!') {
+            // A negated rule presumes success unless a match is found.
+            negated = true;
+            if (*(w+1) == '~')
+                regexp = true;
+            continue;
+        }
+
+        // Figure out if there's a match.
+        bool match = false;
+        if (regexp) {
+            try {
+                // To do regex matching, we have to convert from UTF-8.
+                auto_arrayptr<XMLCh> trans(fromUTF8(w));
+                RegularExpression re(trans.get());
+                auto_arrayptr<XMLCh> trans2(fromUTF8(sta.getRemoteUser().c_str()));
+                match = re.matches(trans2.get());
+            }
+            catch (XMLException& ex) {
+                auto_ptr_char tmp(ex.getMessage());
+                sta.log(SPRequest::SPError,
+                    string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
+            }
+        }
+        else if (sta.getRemoteUser() == w) {
+            match = true;
+        }
+
+        if (match) {
+            if (sta.isPriorityEnabled(SPRequest::SPDebug))
+                sta.log(SPRequest::SPDebug,
+                    string("htaccess: require user ") + (negated ? "rejecting (" : "accepting (") + sta.getRemoteUser() + ")");
+            return (negated ? shib_acl_false : shib_acl_true);
+        }
+    }
+    return (negated ? shib_acl_true : shib_acl_false);
+}
+
+#ifndef SHIB_APACHE_24
+static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
+{
+    SH_AP_CONFIGFILE* f;
+    SH_AP_TABLE* grps=ap_make_table(r->pool,15);
+    char l[MAX_STRING_LEN];
+    const char *group_name, *ll, *w;
+
+#ifdef SHIB_APACHE_13
+    if (!(f=ap_pcfg_openfile(r->pool, grpfile))) {
+#else
+    if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
+#endif
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, SH_AP_R(r), "groups_for_user: could not open group file: %s\n", grpfile);
+        return nullptr;
+    }
+
+    SH_AP_POOL* sp;
+#ifdef SHIB_APACHE_13
+    sp=ap_make_sub_pool(r->pool);
+#else
+    if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
+        ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
+            "groups_for_user: could not create a subpool");
+        return nullptr;
+    }
+#endif
+
+    while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
+        if ((*l=='#') || (!*l))
+            continue;
+        ll = l;
+        ap_clear_pool(sp);
+        group_name = ap_getword(sp,&ll,':');
+        while (*ll) {
+            w=ap_getword_conf(sp,&ll);
+            if (!strcmp(w,user)) {
+                ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
+                break;
+            }
+        }
+    }
+    ap_cfg_closefile(f);
+    ap_destroy_pool(sp);
+    return grps;
+}
+
+AccessControl::aclresult_t htAccessControl::doGroup(const ShibTargetApache& sta, const char* params) const
+{
+    SH_AP_TABLE* grpstatus = nullptr;
+    if (sta.m_dc->szAuthGrpFile) {
+        if (sta.isPriorityEnabled(SPRequest::SPDebug))
+            sta.log(SPRequest::SPDebug, string("htaccess plugin using groups file: ") + sta.m_dc->szAuthGrpFile);
+        grpstatus = groups_for_user(sta.m_req, sta.getRemoteUser().c_str(), sta.m_dc->szAuthGrpFile);
+    }
+
+    bool negated = false;
+    while (*params) {
+        const char* w = ap_getword_conf(sta.m_req->pool, &params);
+        if (*w == '!') {
+            // A negated rule presumes success unless a match is found.
+            negated = true;
+            continue;
+        }
+
+        if (grpstatus && ap_table_get(grpstatus, w)) {
+            // If we matched, then we're done with this rule either way and we flip status to reflect the outcome.
+            sta.log(SPRequest::SPDebug, string("htaccess: require group ") + (negated ? "rejecting (" : "accepting (") + w + ")");
+            return (negated ? shib_acl_false : shib_acl_true);
+        }
+    }
+
+    return (negated ? shib_acl_true : shib_acl_false);
+}
+#endif
+
+AccessControl::aclresult_t htAccessControl::doAuthnContext(const ShibTargetApache& sta, const char* ref, const char* params) const
+{
+    if (ref && *ref) {
+        bool regexp = false;
+        bool negated = false;
+        while (ref && *params) {
+            const char* w = ap_getword_conf(sta.m_req->pool, &params);
+            if (*w == '~') {
+                regexp = true;
+                continue;
+            }
+            else if (*w == '!') {
+                // A negated rule presumes success unless a match is found.
+                negated = true;
+                if (*(w+1) == '~')
+                    regexp = true;
+                continue;
+            }
+
+            // Figure out if there's a match.
+            bool match = false;
+            if (regexp) {
+                try {
+                    RegularExpression re(w);
+                    match = re.matches(ref);
+                }
+                catch (XMLException& ex) {
+                    auto_ptr_char tmp(ex.getMessage());
+                    sta.log(SPRequest::SPError,
+                        string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
+                }
+            }
+            else if (!strcmp(w, ref)) {
+                match = true;
+            }
+
+            if (match) {
+                if (sta.isPriorityEnabled(SPRequest::SPDebug))
+                    sta.log(SPRequest::SPDebug,
+                        string("htaccess: require authnContext ") + (negated ? "rejecting (" : "accepting (") + ref + ")");
+                return (negated ? shib_acl_false : shib_acl_true);
+            }
+        }
+        return (negated ? shib_acl_true : shib_acl_false);
+    }
+
+    if (sta.isPriorityEnabled(SPRequest::SPDebug))
+        sta.log(SPRequest::SPDebug, "htaccess: require authnContext rejecting session with no context associated");
+    return shib_acl_false;
+}
+
+bool htAccessControl::checkAttribute(const SPRequest& request, const Attribute* attr, const char* toMatch, RegularExpression* re) const
+{
+    bool caseSensitive = attr->isCaseSensitive();
+    const vector<string>& vals = attr->getSerializedValues();
+    for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
+        if (re) {
+            auto_arrayptr<XMLCh> trans(fromUTF8(v->c_str()));
+            if (re->matches(trans.get())) {
+                if (request.isPriorityEnabled(SPRequest::SPDebug))
+                    request.log(SPRequest::SPDebug, string("htaccess: expecting regexp ") + toMatch + ", got " + *v + ": accepted");
+                return true;
+            }
+        }
+        else if ((caseSensitive && *v == toMatch) || (!caseSensitive && !strcasecmp(v->c_str(), toMatch))) {
+            if (request.isPriorityEnabled(SPRequest::SPDebug))
+                request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": accepted");
+            return true;
+        }
+        else if (request.isPriorityEnabled(SPRequest::SPDebug)) {
+            request.log(SPRequest::SPDebug, string("htaccess: expecting ") + toMatch + ", got " + *v + ": rejected");
+        }
+    }
+    return false;
+}
+
+AccessControl::aclresult_t htAccessControl::doShibAttr(const ShibTargetApache& sta, const Session* session, const char* rule, const char* params) const
+{
+#ifndef SHIB_APACHE_24
+    // Look for the new shib-attr placeholder and move past it.
+    if (sta.m_dc->bCompatWith24 == 1 && rule && !strcmp(rule, "shib-attr")) {
+        if (*params)
+            rule = ap_getword_conf(sta.m_req->pool, &params);
+    }
+#endif
+
+    // Find the attribute(s) matching the require rule.
+    pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs =
+        session->getIndexedAttributes().equal_range(rule ? rule : "");
+
+    bool regexp = false;
+    while (attrs.first != attrs.second && *params) {
+        const char* w = ap_getword_conf(sta.m_req->pool, &params);
+        if (*w == '~') {
+            regexp = true;
+            continue;
+        }
+
+        try {
+            scoped_ptr<RegularExpression> re;
+            if (regexp) {
+                auto_arrayptr<XMLCh> trans(fromUTF8(w));
+                re.reset(new xercesc::RegularExpression(trans.get()));
+            }
+                    
+            pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> attrs2(attrs);
+            for (; attrs2.first != attrs2.second; ++attrs2.first) {
+                if (checkAttribute(sta, attrs2.first->second, w, regexp ? re.get() : nullptr)) {
+                    return shib_acl_true;
+                }
+            }
+        }
+        catch (XMLException& ex) {
+            auto_ptr_char tmp(ex.getMessage());
+            sta.log(SPRequest::SPError, string("htaccess plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
+        }
+    }
+    return shib_acl_false;
+}
+
+AccessControl::aclresult_t htAccessControl::authorized(const SPRequest& request, const Session* session) const
+{
+#ifdef SHIB_APACHE_24
+    // We should never be invoked in 2.4 as an SP plugin.
+    throw ConfigurationException("Save my walrus!");
+#else
+    // Make sure the object is our type.
+    const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
+    if (!sta)
+        throw ConfigurationException("Request wrapper object was not of correct type.");
+
+    int m = sta->m_req->method_number;
+    bool method_restricted = false;
+    const char *t, *w;
+
+    const array_header* reqs_arr = ap_requires(sta->m_req);
+    if (!reqs_arr)
+        return shib_acl_indeterminate;  // should never happen
+
+	// Check for an "embedded" AccessControl plugin.
+	if (sta->m_dc->szAccessControl) {
+        aclresult_t result = doAccessControl(*sta, session, sta->m_dc->szAccessControl);
+        if (result == shib_acl_true && sta->m_dc->bRequireAll != 1) {
+            // If we're not insisting that all rules be met, then we're done.
+            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was successful, granting access");
+            return shib_acl_true;
+        }
+        else if (result != shib_acl_true && sta->m_dc->bRequireAll == 1) {
+            // If we're insisting that all rules be met, which is not something Apache really handles well,
+            // then we either return false or indeterminate based on the authoritative option, which defaults on.
+            if (sta->m_dc->bAuthoritative != 0) {
+                request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful, denying access");
+                return shib_acl_false;
+            }
+
+            request.log(SPRequest::SPDebug, "htaccess: embedded AccessControl plugin was unsuccessful but not authoritative, leaving it up to Apache");
+            return shib_acl_indeterminate;
+        }
+    }
+
+    require_line* reqs = (require_line*)reqs_arr->elts;
+
+    for (int x = 0; x < reqs_arr->nelts; ++x) {
+        // This rule should be completely ignored, the method doesn't fit.
+        // The rule just doesn't exist for our purposes.
+        if (!(reqs[x].method_mask & (1 << m)))
+            continue;
+
+        method_restricted = true; // this lets us know at the end that at least one rule was potentially enforcable.
+
+        // Tracks status of this rule's evaluation.
+        bool status = false;
+
+        string remote_user = request.getRemoteUser();
+
+        t = reqs[x].requirement;
+        w = ap_getword_white(sta->m_req->pool, &t);
+
+        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.
+
+            // We evaluate to false if ShibAccessControl is used and ShibRequireAll is off.
+            // This allows actual rules to dictate the result, since ShibAccessControl returned
+            // non-true, and if nothing else is used, access will be denied.
+            if (!sta->m_dc->szAccessControl || sta->m_dc->bRequireAll == 1) {
+                // We evaluate to true, because ShibRequireAll is enabled (so a true is just a no-op)
+                // or because there was no other AccessControl rule in place, so this may be the only
+                // rule in effect.
+                status = true;
+            }
+        }
+        else if (!strcmp(w,"valid-user") && session) {
+            request.log(SPRequest::SPDebug, "htaccess: accepting valid-user based on active session");
+            status = true;
+        }
+        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-session") && session) {
+            request.log(SPRequest::SPDebug, "htaccess: accepting shib-session based on active session");
+            status = true;
+        }
+        else if (!strcmp(w,"user") && !remote_user.empty()) {
+            status = (doUser(*sta, t) == shib_acl_true);
+        }
+        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-user") && !remote_user.empty()) {
+            status = (doUser(*sta, t) == shib_acl_true);
+        }
+        else if (!strcmp(w,"group")  && !remote_user.empty()) {
+            status = (doGroup(*sta, t) == shib_acl_true);
+        }
+        else if (!strcmp(w,"authnContextClassRef") || !strcmp(w,"authnContextDeclRef")) {
+            const char* ref = !strcmp(w, "authnContextClassRef") ? session->getAuthnContextClassRef() : session->getAuthnContextDeclRef();
+            status = (doAuthnContext(*sta, ref, t) == shib_acl_true);
+        }
+        else if (!session) {
+            request.log(SPRequest::SPError, string("htaccess: require ") + w + " not given a valid session, are you using lazy sessions?");
+        }
+        else if (sta->m_dc->bCompatWith24 == 1 && !strcmp(w,"shib-plugin")) {
+            w = ap_getword_conf(sta->m_req->pool, &t);
+            if (w) {
+                status = (doAccessControl(*sta, session, w) == shib_acl_true);
+            }
+        }
+        else {
+            status = (doShibAttr(*sta, session, w, t) == shib_acl_true);
+        }
+
+        // If status is false, we found a rule we couldn't satisfy.
+        // Could be an unknown rule to us, or it just didn't match.
+
+        if (status && sta->m_dc->bRequireAll != 1) {
+            // If we're not insisting that all rules be met, then we're done.
+            request.log(SPRequest::SPDebug, "htaccess: a rule was successful, granting access");
+            return shib_acl_true;
+        }
+        else if (!status && sta->m_dc->bRequireAll == 1) {
+            // If we're insisting that all rules be met, which is not something Apache really handles well,
+            // then we either return false or indeterminate based on the authoritative option, which defaults on.
+            if (sta->m_dc->bAuthoritative != 0) {
+                request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful, denying access");
+                return shib_acl_false;
+            }
+
+            request.log(SPRequest::SPDebug, "htaccess: a rule was unsuccessful but not authoritative, leaving it up to Apache");
+            return shib_acl_indeterminate;
+        }
+
+        // Otherwise, we keep going. If we're requring all, then we have to check every rule.
+        // If not we just didn't find a successful rule yet, so we keep going anyway.
+    }
+
+    // If we get here, we either "failed" or we're in require all mode (but not both).
+    // If no rules possibly apply or we insisted that all rules check out, then we're good.
+    if (!method_restricted) {
+        request.log(SPRequest::SPDebug, "htaccess: no rules applied to this request method, granting access");
+        return shib_acl_true;
+    }
+    else if (sta->m_dc->bRequireAll == 1) {
+        request.log(SPRequest::SPDebug, "htaccess: all rules successful, granting access");
+        return shib_acl_true;
+    }
+    else if (sta->m_dc->bAuthoritative != 0) {
+        request.log(SPRequest::SPDebug, "htaccess: no rules were successful, denying access");
+        return shib_acl_false;
+    }
+
+    request.log(SPRequest::SPDebug, "htaccess: no rules were successful but not authoritative, leaving it up to Apache");
+    return shib_acl_indeterminate;
+#endif
+}
+
+class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
+{
+public:
+    ApacheRequestMapper(const xercesc::DOMElement* e);
+    ~ApacheRequestMapper() {}
+    Lockable* lock() { return m_mapper->lock(); }
+    void unlock() { m_staKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
+    Settings getSettings(const HTTPRequest& request) const;
+
+    const PropertySet* getParent() const { return nullptr; }
+    void setParent(const PropertySet*) {}
+    pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
+    pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
+    pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
+    pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
+    pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
+    void getAll(map<string,const char*>& properties) const;
+    const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
+    const xercesc::DOMElement* getElement() const;
+
+    const htAccessControl& getHTAccessControl() const { return m_htaccess; }
+
+private:
+    scoped_ptr<RequestMapper> m_mapper;
+    scoped_ptr<ThreadKey> m_staKey,m_propsKey;
+    mutable htAccessControl m_htaccess;
+};
+
+RequestMapper* ApacheRequestMapFactory(const xercesc::DOMElement* const & e)
+{
+    return new ApacheRequestMapper(e);
+}
+
+ApacheRequestMapper::ApacheRequestMapper(const xercesc::DOMElement* e)
+    : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
+        m_staKey(ThreadKey::create(nullptr)), m_propsKey(ThreadKey::create(nullptr))
+{
+}
+
+RequestMapper::Settings ApacheRequestMapper::getSettings(const HTTPRequest& request) const
+{
+    Settings s = m_mapper->getSettings(request);
+    m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
+    m_propsKey->setData((void*)s.first);
+    // Only return the htAccess plugin for pre-2.4 servers.
+#ifdef SHIB_APACHE_24
+    return pair<const PropertySet*,AccessControl*>(this, s.second);
+#else
+    return pair<const PropertySet*,AccessControl*>(this, s.second ? s.second : &m_htaccess);
+#endif
+}
+
+pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    if (sta && !ns) {
+        // Override Apache-settable boolean properties.
+        if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession != -1)
+            return make_pair(true, sta->m_dc->bRequireSession==1);
+        else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion != -1)
+            return make_pair(true, sta->m_dc->bExportAssertion==1);
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, !strcmp(prop, "true") || !strcmp(prop, "1") || !strcmp(prop, "On"));
+        }
+    }
+    return s ? s->getBool(name,ns) : make_pair(false,false);
+}
+
+pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    if (sta && !ns) {
+        // Override Apache-settable string properties.
+        if (name && !strcmp(name,"authType")) {
+            const char* auth_type = ap_auth_type(sta->m_req);
+            if (auth_type) {
+                // Check for Basic Hijack
+                if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
+                    auth_type = "shibboleth";
+                return make_pair(true, auth_type);
+            }
+        }
+        else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
+            return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
+        else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
+            return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
+        else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+            return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, prop);
+        }
+    }
+    return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
+}
+
+pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
+{
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
+}
+
+pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    if (sta && !ns) {
+        // Override Apache-settable int properties.
+        if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+            return pair<bool,unsigned int>(true, strtol(sta->m_dc->szRedirectToSSL, nullptr, 10));
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return pair<bool,unsigned int>(true, atoi(prop));
+        }
+    }
+    return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
+}
+
+pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    if (sta && !ns) {
+        // Override Apache-settable int properties.
+        if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
+            return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
+        else if (sta->m_dc->tSettings) {
+            const char* prop = ap_table_get(sta->m_dc->tSettings, name);
+            if (prop)
+                return make_pair(true, atoi(prop));
+        }
+    }
+    return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
+}
+
+static int _rm_get_all_table_walk(void *v, const char *key, const char *value)
+{
+    reinterpret_cast<map<string,const char*>*>(v)->insert(pair<string,const char*>(key, value));
+    return 1;
+}
+
+void ApacheRequestMapper::getAll(map<string,const char*>& properties) const
+{
+    const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+
+    if (s)
+        s->getAll(properties);
+    if (!sta)
+        return;
+
+    const char* auth_type=ap_auth_type(sta->m_req);
+    if (auth_type) {
+        // Check for Basic Hijack
+        if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
+            auth_type = "shibboleth";
+        properties["authType"] = auth_type;
+    }
+
+    if (sta->m_dc->szApplicationId)
+        properties["applicationId"] = sta->m_dc->szApplicationId;
+    if (sta->m_dc->szRequireWith)
+        properties["requireSessionWith"] = sta->m_dc->szRequireWith;
+    if (sta->m_dc->szRedirectToSSL)
+        properties["redirectToSSL"] = sta->m_dc->szRedirectToSSL;
+    if (sta->m_dc->bRequireSession != 0)
+        properties["requireSession"] = (sta->m_dc->bRequireSession==1) ? "true" : "false";
+    if (sta->m_dc->bExportAssertion != 0)
+        properties["exportAssertion"] = (sta->m_dc->bExportAssertion==1) ? "true" : "false";
+
+    if (sta->m_dc->tSettings)
+        ap_table_do(_rm_get_all_table_walk, &properties, sta->m_dc->tSettings, NULL);
+}
+
+const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
+{
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    return s ? s->getPropertySet(name,ns) : nullptr;
+}
+
+const xercesc::DOMElement* ApacheRequestMapper::getElement() const
+{
+    const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
+    return s ? s->getElement() : nullptr;
+}
+
+// Authz callbacks for Apache 2.4
+// For some reason, these get run twice for each request, once before hooks like check_user, etc.
+// and once after. The first time through, the request object exists, but isn't initialized.
+// The other case is subrequests of some kinds: then post_read doesn't run, and the objects
+// themselves don't exist. We do deferred creation of the objects in check_user to fix that case.
+// In each screwed up case, we return "denied" so that nothing bad happens.
+#ifdef SHIB_APACHE_24
+pair<ShibTargetApache*,authz_status> shib_base_check_authz(request_rec* r)
+{
+    shib_request_config* rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
+    if (!rc || !rc->sta) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found no per-request structure");
+        return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
+    }
+    else if (!rc->sta->isInitialized()) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "shib_base_check_authz found uninitialized request object");
+        return make_pair((ShibTargetApache*)nullptr, AUTHZ_DENIED_NO_USER);
+    }
+    return make_pair(rc->sta, AUTHZ_GRANTED);
+}
+
+extern "C" authz_status shib_shibboleth_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+    return AUTHZ_GRANTED;
+}
+
+extern "C" authz_status shib_session_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    try {
+        Session* session = sta.first->getSession(false, true, false);
+        Locker slocker(session, false);
+        if (session) {
+            sta.first->log(SPRequest::SPDebug, "htaccess: accepting shib-session/valid-user based on active session");
+            return AUTHZ_GRANTED;
+        }
+    }
+    catch (std::exception& e) {
+        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
+    }
+
+    sta.first->log(SPRequest::SPDebug, "htaccess: denying shib-access/valid-user rule, no active session");
+    return AUTHZ_DENIED_NO_USER;
+}
+
+extern "C" authz_status shib_validuser_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
+    // For now, added a command to restore "normal" semantics for valid-user so that combined deployments can
+    // use valid-user for non-Shibboleth cases and shib-session for the Shibboleth semantic.
+
+    // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
+    // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
+    // that setting from the ServiceProvider class..
+
+    shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
+    if (sc->bCompatValidUser != 1) {
+        return shib_session_check_authz(r, require_line, nullptr);
+    }
+
+    // Reproduce mod_authz_user version...
+
+    if (!r->user) {
+        return AUTHZ_DENIED_NO_USER;
+    }
+
+    return AUTHZ_GRANTED;
+}
+
+extern "C" authz_status shib_ext_user_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
+    if (hta.doUser(*sta.first, require_line) == AccessControl::shib_acl_true)
+        return AUTHZ_GRANTED;
+    return AUTHZ_DENIED;
+}
+
+extern "C" authz_status shib_user_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    // Shouldn't have actually ever hooked this, and now we're in conflict with mod_authz_user over the meaning.
+    // For now, added a command to restore "normal" semantics for user rules so that combined deployments can
+    // use user for non-Shibboleth cases and shib-user for the Shibboleth semantic.
+
+    // In future, we may want to expose the AuthType set to honor down at this level so we can differentiate
+    // based on AuthType. Unfortunately we allow overriding the AuthType to honor and we don't have access to
+    // that setting from the ServiceProvider class..
+
+    shib_server_config* sc = (shib_server_config*)ap_get_module_config(r->server->module_config, &mod_shib);
+    if (sc->bCompatValidUser != 1) {
+        return shib_ext_user_check_authz(r, require_line, nullptr);
+    }
+
+    // Reproduce mod_authz_user version...
+
+    if (!r->user) {
+        return AUTHZ_DENIED_NO_USER;
+    }
+ 	
+    const char* t = require_line;
+    const char *w;
+    while ((w = ap_getword_conf(r->pool, &t)) && w[0]) {
+        if (!strcmp(r->user, w)) {
+            return AUTHZ_GRANTED;
+        }
+    }
+ 	
+    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01663)
+        "access to %s failed, reason: user '%s' does not meet "
+        "'require'ments for user to be allowed access",
+        r->uri, r->user);
+ 	
+    return AUTHZ_DENIED;
+}
+
+extern "C" authz_status shib_acclass_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
+
+    try {
+        Session* session = sta.first->getSession(false, true, false);
+        Locker slocker(session, false);
+        if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextClassRef(), require_line) == AccessControl::shib_acl_true)
+            return AUTHZ_GRANTED;
+        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
+    }
+    catch (std::exception& e) {
+        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
+    }
+
+    return AUTHZ_GENERAL_ERROR;
+}
+
+extern "C" authz_status shib_acdecl_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
+
+    try {
+        Session* session = sta.first->getSession(false, true, false);
+        Locker slocker(session, false);
+        if (session && hta.doAuthnContext(*sta.first, session->getAuthnContextDeclRef(), require_line) == AccessControl::shib_acl_true)
+            return AUTHZ_GRANTED;
+        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
+    }
+    catch (std::exception& e) {
+        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
+    }
+
+    return AUTHZ_GENERAL_ERROR;
+}
+
+extern "C" authz_status shib_attr_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
+
+    try {
+        Session* session = sta.first->getSession(false, true, false);
+        Locker slocker(session, false);
+        if (session) {
+            const char* rule = ap_getword_conf(r->pool, &require_line);
+            if (rule && hta.doShibAttr(*sta.first, session, rule, require_line) == AccessControl::shib_acl_true)
+                return AUTHZ_GRANTED;
+        }
+        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
+    }
+    catch (std::exception& e) {
+        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
+    }
+
+    return AUTHZ_GENERAL_ERROR;
+}
+
+extern "C" authz_status shib_plugin_check_authz(request_rec* r, const char* require_line, const void*)
+{
+    pair<ShibTargetApache*,authz_status> sta = shib_base_check_authz(r);
+    if (!sta.first)
+        return sta.second;
+
+    const htAccessControl& hta = dynamic_cast<const ApacheRequestMapper*>(sta.first->getRequestSettings().first)->getHTAccessControl();
+
+    try {
+        Session* session = sta.first->getSession(false, true, false);
+        Locker slocker(session, false);
+        if (session) {
+            const char* config = ap_getword_conf(r->pool, &require_line);
+            if (config && hta.doAccessControl(*sta.first, session, config) == AccessControl::shib_acl_true)
+                return AUTHZ_GRANTED;
+        }
+        return session ? AUTHZ_DENIED : AUTHZ_DENIED_NO_USER;
+    }
+    catch (std::exception& e) {
+        sta.first->log(SPRequest::SPWarn, string("htaccess: unable to obtain session for access control check: ") +  e.what());
+    }
+
+    return AUTHZ_GENERAL_ERROR;
+}
+#endif
+
+// Command manipulation functions
+
+extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
+{
+    *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
+    return nullptr;
+}
+
+extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
+{
+    char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
+    size_t offset=(size_t)parms->info;
+    *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
+    return nullptr;
+}
+
+extern "C" const char* shib_set_server_flag_slot(cmd_parms* parms, void*, int arg)
+{
+    char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
+    size_t offset=(size_t)parms->info;
+    *((int*)(base + offset)) = arg;
+    return nullptr;
+}
+
+extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
+#ifdef SHIB_APACHE_13
+					     char* arg1, char* arg2
+#else
+					     void* arg1, const char* arg2
+#endif
+					     )
+{
+  ap_set_file_slot(parms, arg1, arg2);
+  return DECLINE_CMD;
+}
+
+extern "C" const char* shib_table_set(cmd_parms* parms, shib_dir_config* dc, const char* arg1, const char* arg2)
+{
+    if (!dc->tSettings)
+        dc->tSettings = ap_make_table(parms->pool, 4);
+    ap_table_set(dc->tSettings, arg1, arg2);
+    return nullptr;
+}
+
+#ifndef SHIB_APACHE_24
+extern "C" const char* shib_set_acl_slot(cmd_parms* params, shib_dir_config* dc, char* arg)
+{
+    bool absolute;
+    switch (*arg) {
+        case 0:
+            absolute = false;
+            break;
+        case '/':
+        case '\\':
+            absolute = true;
+            break;
+        case '.':
+            absolute = (*(arg+1) == '.' || *(arg+1) == '/' || *(arg+1) == '\\');
+            break;
+        default:
+            absolute = *(arg+1) == ':';
+    }
+
+    if (absolute || !params->path)
+        dc->szAccessControl = ap_pstrdup(params->pool, arg);
+    else
+        dc->szAccessControl = ap_pstrcat(params->pool, params->path, arg, NULL);
+    return nullptr;
+}
+#endif
+
+
+#ifdef SHIB_APACHE_13
+/*
+ * shib_child_exit()
+ *  Cleanup the (per-process) pool info.
+ */
+extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
+{
+    if (g_Config) {
+        g_Config->term();
+        g_Config = nullptr;
+    }
+    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "child_exit: mod_shib shutdown in pid (%d)", (int)getpid());
+}
+#else
+/*
+ * shib_exit()
+ *  Apache 2.x doesn't allow for per-child cleanup, causes CGI forks to hang.
+ */
+extern "C" apr_status_t shib_exit(void* data)
+{
+    if (g_Config) {
+        g_Config->term();
+        g_Config = nullptr;
+    }
+    server_rec* s = reinterpret_cast<server_rec*>(data);
+    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s), "shib_exit: mod_shib shutdown in pid (%d)", (int)getpid());
+    return OK;
+}
+
+/*
+ * shib_post_config()
+ *  We do the library init/term work here for 2.x to reduce overhead and
+ *  get default logging established before the fork happens.
+ */
+apr_status_t shib_post_config(apr_pool_t* p, apr_pool_t*, apr_pool_t*, server_rec* s)
+{
+    // Initialize runtime components.
+    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"post_config: mod_shib initializing in pid (%d)", (int)getpid());
+
+    if (g_Config) {
+        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib already initialized");
+        return !OK;
+    }
+
+    g_Config = &SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging |
+        SPConfig::Handlers
+        );
+    if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
+        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "post_config: mod_shib failed to initialize libraries");
+        return !OK;
+    }
+#ifndef SHIB_APACHE_24
+    g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
+#endif
+    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
+
+    // Set the cleanup handler, passing in the server_rec for logging.
+    apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
+
+    return OK;
+}
+
+#endif
+
+/*
+ * shib_child_init()
+ *  Things to do when the child process is initialized.
+ *  We can't use post-config for all of it on 2.x because only the forking thread shows
+ *  up in the child, losing the internal threads spun up by plugins in the SP.
+ */
+#ifdef SHIB_APACHE_13
+extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
+#else
+extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
+#endif
+{
+    // Initialize runtime components.
+
+    ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, SH_AP_R(s),"child_init: mod_shib initializing in pid (%d)", (int)getpid());
+
+    // 2.x versions have already initialized the libraries.
+#ifdef SHIB_APACHE_13
+    if (g_Config) {
+        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib already initialized, exiting");
+        exit(1);
+    }
+
+    g_Config = &SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging |
+        SPConfig::Handlers
+        );
+    if (!g_Config->init(g_szSchemaDir, g_szPrefix)) {
+        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to initialize libraries");
+        exit(1);
+    }
+    g_Config->AccessControlManager.registerFactory(HT_ACCESS_CONTROL, &htAccessFactory);
+    g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, &ApacheRequestMapFactory);
+#endif
+
+    // The config gets installed for all versions here due to the background thread/fork issues.
+    try {
+        if (!g_Config->instantiate(g_szSHIBConfig, true))
+            throw runtime_error("unknown error");
+    }
+    catch (std::exception& ex) {
+        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib failed to load configuration: %s", ex.what());
+        g_Config->term();
+        exit(1);
+    }
+
+    ServiceProvider* sp = g_Config->getServiceProvider();
+    xmltooling::Locker locker(sp);
+    const PropertySet* props = sp->getPropertySet("InProcess");
+    if (props) {
+        pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
+        if (unsetValue.first)
+            g_unsetHeaderValue = unsetValue.second;
+        pair<bool,bool> flag=props->getBool("checkSpoofing");
+        g_checkSpoofing = !flag.first || flag.second;
+        if (g_checkSpoofing) {
+            unsetValue=props->getString("spoofKey");
+            if (unsetValue.first)
+                g_spoofKey = unsetValue.second;
+        }
+        flag=props->getBool("catchAll");
+        g_catchAll = flag.first && flag.second;
+    }
+
+    // Set the cleanup handler, passing in the server_rec for logging.
+    apr_pool_cleanup_register(p, s, &shib_exit, apr_pool_cleanup_null);
+
+    ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(s), "child_init: mod_shib config initialized");
+}
+
+// Output filters
+#ifdef SHIB_DEFERRED_HEADERS
+static void set_output_filter(request_rec *r)
+{
+   ap_add_output_filter("SHIB_HEADERS_OUT", nullptr, r, r->connection);
+}
+
+static void set_error_filter(request_rec *r)
+{
+   ap_add_output_filter("SHIB_HEADERS_ERR", nullptr, r, r->connection);
+}
+
+static int _table_add(void *v, const char *key, const char *value)
+{
+    apr_table_addn((apr_table_t*)v, key, value);
+    return 1;
+}
+
+static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
+{
+    request_rec *r = f->r;
+    shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
+
+    if (rc && rc->hdr_out) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "output_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
+        // can't use overlap call because it will collapse Set-Cookie headers
+        //apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
+        apr_table_do(_table_add,r->headers_out, rc->hdr_out,NULL);
+    }
+
+    /* remove ourselves from the filter chain */
+    ap_remove_output_filter(f);
+
+    /* send the data up the stack */
+    return ap_pass_brigade(f->next,in);
+}
+
+static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
+{
+    request_rec *r = f->r;
+    shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
+
+    if (rc && rc->hdr_out) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, SH_AP_R(r), "error_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
+        // can't use overlap call because it will collapse Set-Cookie headers
+        //apr_table_overlap(r->err_headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
+        apr_table_do(_table_add,r->err_headers_out, rc->hdr_out,NULL);
+    }
+
+    /* remove ourselves from the filter chain */
+    ap_remove_output_filter(f);
+
+    /* send the data up the stack */
+    return ap_pass_brigade(f->next,in);
+}
+#endif // SHIB_DEFERRED_HEADERS
+
+typedef const char* (*config_fn_t)(void);
+
+#ifdef SHIB_APACHE_13
+
+// SHIB Module commands
+
+static command_rec shire_cmds[] = {
+  {"ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
+   RSRC_CONF, TAKE1, "Shibboleth installation directory"},
+  {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
+   RSRC_CONF, TAKE1, "Path to shibboleth2.xml config file"},
+  {"ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+   RSRC_CONF, TAKE1, "Paths of XML schema catalogs"},
+
+  {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
+   (void *) XtOffsetOf (shib_server_config, szScheme),
+   RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
+
+  {"ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
+   OR_AUTHCFG, TAKE2, "Set arbitrary Shibboleth request property for content"},
+
+  {"ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
+   OR_AUTHCFG, TAKE1, "Set arbitrary Shibboleth access control plugin for content"},
+
+  {"ShibDisable", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bOff),
+   OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
+  {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
+   (void *) XtOffsetOf (shib_dir_config, szApplicationId),
+   OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
+  {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
+   OR_AUTHCFG, FLAG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"},
+  {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bRequireSession),
+   OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
+  {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
+   (void *) XtOffsetOf (shib_dir_config, szRequireWith),
+   OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
+  {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
+   OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
+  {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
+   (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
+   OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
+  {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
+   (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
+   OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
+  {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bRequireAll),
+   OR_AUTHCFG, FLAG, "All require directives must match"},
+  {"AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bAuthoritative),
+   OR_AUTHCFG, FLAG, "Allow failed mod_shib htaccess authorization to fall through to other modules"},
+  {"ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bCompatWith24),
+   OR_AUTHCFG, FLAG, "Support Apache 2.4-style require rules"},
+  {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
+   OR_AUTHCFG, FLAG, "Export attributes using environment variables (default)"},
+  {"ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bUseHeaders),
+   OR_AUTHCFG, FLAG, "Export attributes using custom HTTP headers"},
+  {"ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
+   (void *) XtOffsetOf (shib_dir_config, bExpireRedirects),
+   OR_AUTHCFG, FLAG, "Expire SP-generated redirects"},
+
+  {nullptr}
+};
+
+extern "C"{
+handler_rec shib_handlers[] = {
+  { "shib-handler", shib_handler },
+  { nullptr }
+};
+
+module MODULE_VAR_EXPORT mod_shib = {
+    STANDARD_MODULE_STUFF,
+    nullptr,                        /* initializer */
+    create_shib_dir_config,	/* dir config creater */
+    merge_shib_dir_config,	/* dir merger --- default is to override */
+    create_shib_server_config, /* server config */
+    merge_shib_server_config,   /* merge server config */
+    shire_cmds,			/* command table */
+    shib_handlers,		/* handlers */
+    nullptr,			/* filename translation */
+    shib_check_user,		/* check_user_id */
+    shib_auth_checker,		/* check auth */
+    nullptr,			/* check access */
+    nullptr,			/* type_checker */
+    shib_fixups,		/* fixups */
+    nullptr,			/* logger */
+    nullptr,			/* header parser */
+    shib_child_init,		/* child_init */
+    shib_child_exit,		/* child_exit */
+    shib_post_read		/* post read-request */
+};
+
+#else
+
+#ifdef SHIB_APACHE_24
+extern "C" const authz_provider shib_authz_shibboleth_provider = { &shib_shibboleth_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_validuser_provider = { &shib_validuser_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_session_provider = { &shib_session_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_user_provider = { &shib_user_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_ext_user_provider = { &shib_ext_user_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_acclass_provider = { &shib_acclass_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_acdecl_provider = { &shib_acdecl_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_attr_provider = { &shib_attr_check_authz, nullptr };
+extern "C" const authz_provider shib_authz_plugin_provider = { &shib_plugin_check_authz, nullptr };
+#endif
+
+extern "C" void shib_register_hooks (apr_pool_t *p)
+{
+#ifdef SHIB_DEFERRED_HEADERS
+    ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, nullptr, AP_FTYPE_CONTENT_SET);
+    ap_hook_insert_filter(set_output_filter, nullptr, nullptr, APR_HOOK_LAST);
+    ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, nullptr, AP_FTYPE_CONTENT_SET);
+    ap_hook_insert_error_filter(set_error_filter, nullptr, nullptr, APR_HOOK_LAST);
+    ap_hook_post_read_request(shib_post_read, nullptr, nullptr, APR_HOOK_MIDDLE);
+#endif
+    ap_hook_post_config(shib_post_config, nullptr, nullptr, APR_HOOK_MIDDLE);
+    ap_hook_child_init(shib_child_init, nullptr, nullptr, APR_HOOK_MIDDLE);
+    const char* prereq = getenv("SHIBSP_APACHE_PREREQ");
+#ifdef SHIB_APACHE_24
+    if (prereq && *prereq) {
+        const char* const authnPre[] = { prereq, nullptr };
+        ap_hook_check_authn(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
+    }
+    else {
+        ap_hook_check_authn(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_URI);
+    }
+    ap_hook_check_authz(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST, AP_AUTH_INTERNAL_PER_URI);
+#else
+    if (prereq && *prereq) {
+        const char* const authnPre[] = { prereq, nullptr };
+        ap_hook_check_user_id(shib_check_user, authnPre, nullptr, APR_HOOK_MIDDLE);
+    }
+    else {
+        ap_hook_check_user_id(shib_check_user, nullptr, nullptr, APR_HOOK_MIDDLE);
+    }
+    ap_hook_auth_checker(shib_auth_checker, nullptr, nullptr, APR_HOOK_FIRST);
+#endif
+    ap_hook_handler(shib_handler, nullptr, nullptr, APR_HOOK_LAST);
+    ap_hook_fixups(shib_fixups, nullptr, nullptr, APR_HOOK_MIDDLE);
+
+#ifdef SHIB_APACHE_24
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shibboleth", AUTHZ_PROVIDER_VERSION, &shib_authz_shibboleth_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "valid-user", AUTHZ_PROVIDER_VERSION, &shib_authz_validuser_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-session", AUTHZ_PROVIDER_VERSION, &shib_authz_session_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "user", AUTHZ_PROVIDER_VERSION, &shib_authz_user_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-user", AUTHZ_PROVIDER_VERSION, &shib_authz_ext_user_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextClassRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acclass_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "authnContextDeclRef", AUTHZ_PROVIDER_VERSION, &shib_authz_acdecl_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-attr", AUTHZ_PROVIDER_VERSION, &shib_authz_attr_provider, AP_AUTH_INTERNAL_PER_CONF);
+    ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "shib-plugin", AUTHZ_PROVIDER_VERSION, &shib_authz_plugin_provider, AP_AUTH_INTERNAL_PER_CONF);
+#endif
+}
+
+// SHIB Module commands
+
+extern "C" {
+static command_rec shib_cmds[] = {
+    AP_INIT_TAKE1("ShibPrefix", (config_fn_t)ap_set_global_string_slot, &g_szPrefix,
+        RSRC_CONF, "Shibboleth installation directory"),
+    AP_INIT_TAKE1("ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
+        RSRC_CONF, "Path to shibboleth2.xml config file"),
+    AP_INIT_TAKE1("ShibCatalogs", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
+        RSRC_CONF, "Paths of XML schema catalogs"),
+    AP_INIT_TAKE1("ShibGSSKey", (config_fn_t)ap_set_global_string_slot, &g_szGSSContextKey,
+        RSRC_CONF, "Name of user data key containing GSS context established by GSS module"),
+
+    AP_INIT_TAKE1("ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
+        (void *) offsetof (shib_server_config, szScheme),
+        RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
+
+    AP_INIT_TAKE2("ShibRequestSetting", (config_fn_t)shib_table_set, nullptr,
+        OR_AUTHCFG, "Set arbitrary Shibboleth request property for content"),
+
+    AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bOff),
+        OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
+    AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
+        (void *) offsetof (shib_dir_config, szApplicationId),
+        OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
+    AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bBasicHijack),
+        OR_AUTHCFG, "(DEPRECATED) Respond to AuthType Basic and convert to shibboleth"),
+    AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bRequireSession),
+        OR_AUTHCFG, "Initiates a new session if one does not exist"),
+    AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
+        (void *) offsetof (shib_dir_config, szRequireWith),
+        OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
+    AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bExportAssertion),
+        OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
+    AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
+        (void *) offsetof (shib_dir_config, szRedirectToSSL),
+        OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
+#ifdef SHIB_APACHE_24
+    AP_INIT_FLAG("ShibRequestMapperAuthz", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bRequestMapperAuthz),
+        OR_AUTHCFG, "Support access control via shibboleth2.xml / RequestMapper"),
+    AP_INIT_FLAG("ShibCompatValidUser", (config_fn_t)shib_set_server_flag_slot,
+        (void *) offsetof (shib_server_config, bCompatValidUser),
+        RSRC_CONF, "Handle 'require valid-user' in mod_authz_user-compatible fashion (requiring username)"),
+#else
+    AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
+        (void *) offsetof (shib_dir_config, szAuthGrpFile),
+        OR_AUTHCFG, "Text file containing group names and member user IDs"),
+    AP_INIT_TAKE1("ShibAccessControl", (config_fn_t)shib_set_acl_slot, nullptr,
+        OR_AUTHCFG, "Set arbitrary Shibboleth access control plugin for content"),
+    AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bRequireAll),
+        OR_AUTHCFG, "All require directives must match"),
+    AP_INIT_FLAG("AuthzShibAuthoritative", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bAuthoritative),
+        OR_AUTHCFG, "Allow failed mod_shib htaccess authorization to fall through to other modules"),
+    AP_INIT_FLAG("ShibCompatWith24", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bCompatWith24),
+        OR_AUTHCFG, "Support Apache 2.4-style require rules"),
+#endif
+    AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bUseEnvVars),
+        OR_AUTHCFG, "Export attributes using environment variables (default)"),
+    AP_INIT_FLAG("ShibUseHeaders", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bUseHeaders),
+        OR_AUTHCFG, "Export attributes using custom HTTP headers"),
+    AP_INIT_FLAG("ShibExpireRedirects", (config_fn_t)ap_set_flag_slot,
+        (void *) offsetof (shib_dir_config, bExpireRedirects),
+        OR_AUTHCFG, "Expire SP-generated redirects"),
+
+    {nullptr}
+};
+
+module AP_MODULE_DECLARE_DATA mod_shib = {
+    STANDARD20_MODULE_STUFF,
+    create_shib_dir_config,     /* create dir config */
+    merge_shib_dir_config,      /* merge dir config --- default is to override */
+    create_shib_server_config,  /* create server config */
+    merge_shib_server_config,   /* merge server config */
+    shib_cmds,                  /* command table */
+    shib_register_hooks         /* register hooks */
+};
+
+#endif
+
+}
diff --git a/config_win32.h b/config_win32.h
index 9078e33..93ef9cb 100644
--- a/config_win32.h
+++ b/config_win32.h
@@ -1,163 +1,163 @@
-/**
- * Licensed to the University Corporation for Advanced Internet
- * Development, Inc. (UCAID) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for
- * additional information regarding copyright ownership.
- *
- * UCAID licenses this file to you 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
- *
- * 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.
- */
-
-/* config.h.  Generated by configure.  */
-/* config.h.in.  Generated from configure.ac by autoheader.  */
-
-/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
-   don't. */
-#define HAVE_DECL_STRERROR_R 0
-
-/* Define to 1 if you have the declaration of `svcfd_create', and to 0 if you
-   don't. */
-#define HAVE_DECL_SVCFD_CREATE 1
-
-/* Define to 1 if you have the declaration of `sys_errlist', and to 0 if you
-   don't. */
-/* #undef HAVE_DECL_SYS_ERRLIST */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef HAVE_DLFCN_H */
-
-/* Define to 1 if you have the `gmtime_r' function. */
-/* #undef HAVE_GMTIME_R */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `dmallocxx' library (-ldmallocxx). */
-/* #undef HAVE_LIBDMALLOCXX */
-
-/* Define if log4shib library is used. */
-#define SHIBSP_LOG4SHIB 1
-
-/* Define if log4cpp library is used. */
-/* #undef SHIBSP_LOG4CPP */
-
-#include <xercesc/util/XercesVersion.hpp>
-
-#if (XERCES_VERSION_MAJOR < 3)
-# define SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE 1
-# define SHIBSP_XERCESC_SHORT_ACCEPTNODE 1
-#endif
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* define if the compiler implements namespaces */
-#define HAVE_NAMESPACES 1
-
-/* Define if you have POSIX threads libraries and header files. */
-/* #undef HAVE_PTHREAD */
-
-#ifndef SHIBSP_LITE
-# include <xsec/framework/XSECDefs.hpp>
-# if (_XSEC_VERSION_FULL >= 10600)
-#  define SHIBSP_XMLSEC_WHITELISTING 1
-# endif
-#endif
-
-/* Define to 1 if you have the <stdint.h> header file. */
-/* #undef HAVE_STDINT_H */
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the `strcasecmp' function. */
-/* #undef HAVE_STRCASECMP */
-
-/* Define to 1 if you have the `strchr' function. */
-#define HAVE_STRCHR 1
-
-/* Define to 1 if you have the `strdup' function. */
-#define HAVE_STRDUP 1
-
-/* Define to 1 if you have the `strftime' function. */
-#define HAVE_STRFTIME 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strstr' function. */
-#define HAVE_STRSTR 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-/* #undef HAVE_STRTOK_R */
-
-/* Define to 1 if the system has the type `struct rpcent'. */
-/* #undef HAVE_STRUCT_RPCENT */
-
-/* Define to 1 if you have the `strerror_r' function. */
-/* #undef HAVE_STRERROR_R */
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the `timegm' function. */
-/* #undef HAVE_TIMEGM */
-
-/* Define to 1 if you have the <unistd.h> header file. */
-/* #undef HAVE_UNISTD_H */
-
-/* Define to 1 if the system has the type `struct sockaddr_storage'. */
-#define HAVE_STRUCT_SOCKADDR_STORAGE 1
-
-/* Name of package */
-#define PACKAGE "shibboleth"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "https://issues.shibboleth.net/"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "shibboleth"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "shibboleth 2.5.6"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "shibboleth-sp"
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "2.5.6"
-
-/* Define to the necessary symbol if this constant uses a non-standard name on
-   your system. */
-/* #undef PTHREAD_CREATE_JOINABLE */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if your <sys/time.h> declares `struct tm'. */
-/* #undef TM_IN_SYS_TIME */
-
-/* Version number of package */
-#define VERSION "2.5.6"
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `unsigned' if <sys/types.h> does not define. */
-/* #undef size_t */
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
+ *
+ * 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.
+ */
+
+/* config.h.  Generated by configure.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
+   don't. */
+#define HAVE_DECL_STRERROR_R 0
+
+/* Define to 1 if you have the declaration of `svcfd_create', and to 0 if you
+   don't. */
+#define HAVE_DECL_SVCFD_CREATE 1
+
+/* Define to 1 if you have the declaration of `sys_errlist', and to 0 if you
+   don't. */
+/* #undef HAVE_DECL_SYS_ERRLIST */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef HAVE_DLFCN_H */
+
+/* Define to 1 if you have the `gmtime_r' function. */
+/* #undef HAVE_GMTIME_R */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `dmallocxx' library (-ldmallocxx). */
+/* #undef HAVE_LIBDMALLOCXX */
+
+/* Define if log4shib library is used. */
+#define SHIBSP_LOG4SHIB 1
+
+/* Define if log4cpp library is used. */
+/* #undef SHIBSP_LOG4CPP */
+
+#include <xercesc/util/XercesVersion.hpp>
+
+#if (XERCES_VERSION_MAJOR < 3)
+# define SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE 1
+# define SHIBSP_XERCESC_SHORT_ACCEPTNODE 1
+#endif
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* define if the compiler implements namespaces */
+#define HAVE_NAMESPACES 1
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef HAVE_PTHREAD */
+
+#ifndef SHIBSP_LITE
+# include <xsec/framework/XSECDefs.hpp>
+# if (_XSEC_VERSION_FULL >= 10600)
+#  define SHIBSP_XMLSEC_WHITELISTING 1
+# endif
+#endif
+
+/* Define to 1 if you have the <stdint.h> header file. */
+/* #undef HAVE_STDINT_H */
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `strcasecmp' function. */
+/* #undef HAVE_STRCASECMP */
+
+/* Define to 1 if you have the `strchr' function. */
+#define HAVE_STRCHR 1
+
+/* Define to 1 if you have the `strdup' function. */
+#define HAVE_STRDUP 1
+
+/* Define to 1 if you have the `strftime' function. */
+#define HAVE_STRFTIME 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strstr' function. */
+#define HAVE_STRSTR 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+/* #undef HAVE_STRTOK_R */
+
+/* Define to 1 if the system has the type `struct rpcent'. */
+/* #undef HAVE_STRUCT_RPCENT */
+
+/* Define to 1 if you have the `strerror_r' function. */
+/* #undef HAVE_STRERROR_R */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the `timegm' function. */
+/* #undef HAVE_TIMEGM */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #undef HAVE_UNISTD_H */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Name of package */
+#define PACKAGE "shibboleth"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "https://issues.shibboleth.net/"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "shibboleth"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "shibboleth 2.5.6"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "shibboleth-sp"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "2.5.6"
+
+/* Define to the necessary symbol if this constant uses a non-standard name on
+   your system. */
+/* #undef PTHREAD_CREATE_JOINABLE */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+/* #undef TM_IN_SYS_TIME */
+
+/* Version number of package */
+#define VERSION "2.5.6"
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+/* #undef size_t */
diff --git a/configs/shibboleth2.xml b/configs/shibboleth2.xml
index eb69204..44db35d 100644
--- a/configs/shibboleth2.xml
+++ b/configs/shibboleth2.xml
@@ -1,124 +1,124 @@
-<SPConfig xmlns="urn:mace:shibboleth:2.0:native:sp:config"
-    xmlns:conf="urn:mace:shibboleth:2.0:native:sp:config"
-    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
-    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"    
-    xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
-    clockSkew="180">
-
-    <!--
-    By default, in-memory StorageService, ReplayCache, ArtifactMap, and SessionCache
-    are used. See example-shibboleth2.xml for samples of explicitly configuring them.
-    -->
-
-    <!--
-    To customize behavior for specific resources on Apache, and to link vhosts or
-    resources to ApplicationOverride settings below, use web server options/commands.
-    See https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPConfigurationElements for help.
-    
-    For examples with the RequestMap XML syntax instead, see the example-shibboleth2.xml
-    file, and the https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPRequestMapHowTo topic.
-    -->
-
-    <!-- The ApplicationDefaults element is where most of Shibboleth's SAML bits are defined. -->
-    <ApplicationDefaults entityID="https://sp.example.org/shibboleth"
-                         REMOTE_USER="eppn persistent-id targeted-id">
-
-        <!--
-        Controls session lifetimes, address checks, cookie handling, and the protocol handlers.
-        You MUST supply an effectively unique handlerURL value for each of your applications.
-        The value defaults to /Shibboleth.sso, and should be a relative path, with the SP computing
-        a relative value based on the virtual host. Using handlerSSL="true", the default, will force
-        the protocol to be https. You should also set cookieProps to "https" for SSL-only sites.
-        Note that while we default checkAddress to "false", this has a negative impact on the
-        security of your site. Stealing sessions via cookie theft is much easier with this disabled.
-        -->
-        <Sessions lifetime="28800" timeout="3600" relayState="ss:mem"
-                  checkAddress="false" handlerSSL="false" cookieProps="http">
-
-            <!--
-            Configures SSO for a default IdP. To allow for >1 IdP, remove
-            entityID property and adjust discoveryURL to point to discovery service.
-            (Set discoveryProtocol to "WAYF" for legacy Shibboleth WAYF support.)
-            You can also override entityID on /Login query string, or in RequestMap/htaccess.
-            -->
-            <SSO entityID="https://idp.example.org/idp/shibboleth"
-                 discoveryProtocol="SAMLDS" discoveryURL="https://ds.example.org/DS/WAYF">
-              SAML2 SAML1
-            </SSO>
-
-            <!-- SAML and local-only logout. -->
-            <Logout>SAML2 Local</Logout>
-            
-            <!-- Extension service that generates "approximate" metadata based on SP configuration. -->
-            <Handler type="MetadataGenerator" Location="/Metadata" signing="false"/>
-
-            <!-- Status reporting service. -->
-            <Handler type="Status" Location="/Status" acl="127.0.0.1 ::1"/>
-
-            <!-- Session diagnostic service. -->
-            <Handler type="Session" Location="/Session" showAttributeValues="false"/>
-
-            <!-- JSON feed of discovery information. -->
-            <Handler type="DiscoveryFeed" Location="/DiscoFeed"/>
-        </Sessions>
-
-        <!--
-        Allows overriding of error template information/filenames. You can
-        also add attributes with values that can be plugged into the templates.
-        -->
-        <Errors supportContact="root at localhost"
-            helpLocation="/about.html"
-            styleSheet="/shibboleth-sp/main.css"/>
-        
-        <!-- Example of remotely supplied batch of signed metadata. -->
-        <!--
-        <MetadataProvider type="XML" validate="true"
-	      uri="http://example.org/federation-metadata.xml"
-              backingFilePath="federation-metadata.xml" reloadInterval="7200">
-            <MetadataFilter type="RequireValidUntil" maxValidityInterval="2419200"/>
-            <MetadataFilter type="Signature" certificate="fedsigner.pem"/>
-            <DiscoveryFilter type="Blacklist" matcher="EntityAttributes" trimTags="true" 
-              attributeName="http://macedir.org/entity-category"
-              attributeNameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
-              attributeValue="http://refeds.org/category/hide-from-discovery" />
-        </MetadataProvider>
-        -->
-
-        <!-- Example of locally maintained metadata. -->
-        <!--
-        <MetadataProvider type="XML" validate="true" file="partner-metadata.xml"/>
-        -->
-
-        <!-- Map to extract attributes from SAML assertions. -->
-        <AttributeExtractor type="XML" validate="true" reloadChanges="false" path="attribute-map.xml"/>
-        
-        <!-- Use a SAML query if no attributes are supplied during SSO. -->
-        <AttributeResolver type="Query" subjectMatch="true"/>
-
-        <!-- Default filtering policy for recognized attributes, lets other data pass. -->
-        <AttributeFilter type="XML" validate="true" path="attribute-policy.xml"/>
-
-        <!-- Simple file-based resolver for using a single keypair. -->
-        <CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>
-
-        <!--
-        The default settings can be overridden by creating ApplicationOverride elements (see
-        the https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApplicationOverride topic).
-        Resource requests are mapped by web server commands, or the RequestMapper, to an
-        applicationId setting.
-        
-        Example of a second application (for a second vhost) that has a different entityID.
-        Resources on the vhost would map to an applicationId of "admin":
-        -->
-        <!--
-        <ApplicationOverride id="admin" entityID="https://admin.example.org/shibboleth"/>
-        -->
-    </ApplicationDefaults>
-    
-    <!-- Policies that determine how to process and authenticate runtime messages. -->
-    <SecurityPolicyProvider type="XML" validate="true" path="security-policy.xml"/>
-
-    <!-- Low-level configuration about protocols and bindings available for use. -->
-    <ProtocolProvider type="XML" validate="true" reloadChanges="false" path="protocols.xml"/>
-
-</SPConfig>
+<SPConfig xmlns="urn:mace:shibboleth:2.0:native:sp:config"
+    xmlns:conf="urn:mace:shibboleth:2.0:native:sp:config"
+    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
+    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"    
+    xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
+    clockSkew="180">
+
+    <!--
+    By default, in-memory StorageService, ReplayCache, ArtifactMap, and SessionCache
+    are used. See example-shibboleth2.xml for samples of explicitly configuring them.
+    -->
+
+    <!--
+    To customize behavior for specific resources on Apache, and to link vhosts or
+    resources to ApplicationOverride settings below, use web server options/commands.
+    See https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPConfigurationElements for help.
+    
+    For examples with the RequestMap XML syntax instead, see the example-shibboleth2.xml
+    file, and the https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPRequestMapHowTo topic.
+    -->
+
+    <!-- The ApplicationDefaults element is where most of Shibboleth's SAML bits are defined. -->
+    <ApplicationDefaults entityID="https://sp.example.org/shibboleth"
+                         REMOTE_USER="eppn persistent-id targeted-id">
+
+        <!--
+        Controls session lifetimes, address checks, cookie handling, and the protocol handlers.
+        You MUST supply an effectively unique handlerURL value for each of your applications.
+        The value defaults to /Shibboleth.sso, and should be a relative path, with the SP computing
+        a relative value based on the virtual host. Using handlerSSL="true", the default, will force
+        the protocol to be https. You should also set cookieProps to "https" for SSL-only sites.
+        Note that while we default checkAddress to "false", this has a negative impact on the
+        security of your site. Stealing sessions via cookie theft is much easier with this disabled.
+        -->
+        <Sessions lifetime="28800" timeout="3600" relayState="ss:mem"
+                  checkAddress="false" handlerSSL="false" cookieProps="http">
+
+            <!--
+            Configures SSO for a default IdP. To allow for >1 IdP, remove
+            entityID property and adjust discoveryURL to point to discovery service.
+            (Set discoveryProtocol to "WAYF" for legacy Shibboleth WAYF support.)
+            You can also override entityID on /Login query string, or in RequestMap/htaccess.
+            -->
+            <SSO entityID="https://idp.example.org/idp/shibboleth"
+                 discoveryProtocol="SAMLDS" discoveryURL="https://ds.example.org/DS/WAYF">
+              SAML2 SAML1
+            </SSO>
+
+            <!-- SAML and local-only logout. -->
+            <Logout>SAML2 Local</Logout>
+            
+            <!-- Extension service that generates "approximate" metadata based on SP configuration. -->
+            <Handler type="MetadataGenerator" Location="/Metadata" signing="false"/>
+
+            <!-- Status reporting service. -->
+            <Handler type="Status" Location="/Status" acl="127.0.0.1 ::1"/>
+
+            <!-- Session diagnostic service. -->
+            <Handler type="Session" Location="/Session" showAttributeValues="false"/>
+
+            <!-- JSON feed of discovery information. -->
+            <Handler type="DiscoveryFeed" Location="/DiscoFeed"/>
+        </Sessions>
+
+        <!--
+        Allows overriding of error template information/filenames. You can
+        also add attributes with values that can be plugged into the templates.
+        -->
+        <Errors supportContact="root at localhost"
+            helpLocation="/about.html"
+            styleSheet="/shibboleth-sp/main.css"/>
+        
+        <!-- Example of remotely supplied batch of signed metadata. -->
+        <!--
+        <MetadataProvider type="XML" validate="true"
+	      uri="http://example.org/federation-metadata.xml"
+              backingFilePath="federation-metadata.xml" reloadInterval="7200">
+            <MetadataFilter type="RequireValidUntil" maxValidityInterval="2419200"/>
+            <MetadataFilter type="Signature" certificate="fedsigner.pem"/>
+            <DiscoveryFilter type="Blacklist" matcher="EntityAttributes" trimTags="true" 
+              attributeName="http://macedir.org/entity-category"
+              attributeNameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
+              attributeValue="http://refeds.org/category/hide-from-discovery" />
+        </MetadataProvider>
+        -->
+
+        <!-- Example of locally maintained metadata. -->
+        <!--
+        <MetadataProvider type="XML" validate="true" file="partner-metadata.xml"/>
+        -->
+
+        <!-- Map to extract attributes from SAML assertions. -->
+        <AttributeExtractor type="XML" validate="true" reloadChanges="false" path="attribute-map.xml"/>
+        
+        <!-- Use a SAML query if no attributes are supplied during SSO. -->
+        <AttributeResolver type="Query" subjectMatch="true"/>
+
+        <!-- Default filtering policy for recognized attributes, lets other data pass. -->
+        <AttributeFilter type="XML" validate="true" path="attribute-policy.xml"/>
+
+        <!-- Simple file-based resolver for using a single keypair. -->
+        <CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>
+
+        <!--
+        The default settings can be overridden by creating ApplicationOverride elements (see
+        the https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApplicationOverride topic).
+        Resource requests are mapped by web server commands, or the RequestMapper, to an
+        applicationId setting.
+        
+        Example of a second application (for a second vhost) that has a different entityID.
+        Resources on the vhost would map to an applicationId of "admin":
+        -->
+        <!--
+        <ApplicationOverride id="admin" entityID="https://admin.example.org/shibboleth"/>
+        -->
+    </ApplicationDefaults>
+    
+    <!-- Policies that determine how to process and authenticate runtime messages. -->
+    <SecurityPolicyProvider type="XML" validate="true" path="security-policy.xml"/>
+
+    <!-- Low-level configuration about protocols and bindings available for use. -->
+    <ProtocolProvider type="XML" validate="true" reloadChanges="false" path="protocols.xml"/>
+
+</SPConfig>
diff --git a/configure.ac b/configure.ac
index ae51a66..d9b563e 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,1381 +1,1381 @@
-AC_PREREQ([2.50])
-AC_INIT([shibboleth],[2.5.6],[https://issues.shibboleth.net/],[shibboleth-sp])
-AC_CONFIG_SRCDIR(shibsp)
-AC_CONFIG_AUX_DIR(build-aux)
-AC_CONFIG_MACRO_DIR(m4)
-AM_INIT_AUTOMAKE
-AC_DISABLE_STATIC
-AC_PROG_LIBTOOL
-
-# Docygen features
-DX_HTML_FEATURE(ON)
-DX_CHM_FEATURE(OFF)
-DX_CHI_FEATURE(OFF)
-DX_MAN_FEATURE(OFF)
-DX_RTF_FEATURE(OFF)
-DX_XML_FEATURE(OFF)
-DX_PDF_FEATURE(OFF)
-DX_PS_FEATURE(OFF)
-DX_INIT_DOXYGEN(shibboleth, doxygen.cfg, doc/api)
-DX_INCLUDE=
-
-AC_ARG_ENABLE(debug,
-    AS_HELP_STRING([--enable-debug],[Have GCC compile with symbols (Default = no)]),
-    enable_debug=$enableval, enable_debug=no)
-
-if test "$enable_debug" = "yes" ; then
-    GCC_CFLAGS="$CFLAGS -g -D_DEBUG"
-    GCC_CXXFLAGS="$CXXFLAGS -g -D_DEBUG"
-else
-    GCC_CFLAGS="$CFLAGS -O2 -DNDEBUG"
-    GCC_CXXFLAGS="$CXXFLAGS -O2 -DNDEBUG"
-fi
-
-AC_CONFIG_HEADERS([config.h shibsp/config_pub.h])
-AC_CONFIG_FILES([shibboleth.spec])
-
-AC_PROG_CC([gcc gcc3 cc])
-AC_PROG_CXX([g++ g++3 c++ CC])
-AC_CANONICAL_HOST
-
-if test "$GCC" = "yes" ; then
-#    AC_HAVE_GCC_VERSION(4,0,0,0,
-#        [
-#        AC_DEFINE(GCC_HASCLASSVISIBILITY,1,
-#            [Define to enable class visibility control in gcc.])
-#        GCC_CFLAGS="$GCC_CFLAGS -fvisibility=hidden -fvisibility-inlines-hidden"
-#        GCC_CXXFLAGS="$GCC_CXXFLAGS -fvisibility=hidden -fvisibility-inlines-hidden"
-#        ])
-    CFLAGS="-Wall $GCC_CFLAGS"
-    CXXFLAGS="-Wall $GCC_CXXFLAGS"
-fi
-
-# Fix for Sun Workshop compiler in debug mode, may be Sun case #6360993
-# Also enables POSIX semantics for some functions.
-case "${host_cpu}-${host_os}" in
-    *solaris*)
-	CFLAGS="$CFLAGS -D_POSIX_PTHREAD_SEMANTICS"
-	CXXFLAGS="$CXXFLAGS -D_POSIX_PTHREAD_SEMANTICS"
-	if test "$CXX" = "CC" ; then
-		CXXFLAGS="$CXXFLAGS -Qoption ccfe -stabs=no%dfltlit+no%dflthlp"
-	fi
-    ;;
-	*osf*)
-	CXXFLAGS="$CXXFLAGS -D_POSIX_PII_SOCKET"
-	;;
-esac
-
-AC_LANG(C)
-
-# Checks for typedefs, structures, and compiler characteristics.
-AC_C_CONST
-AC_TYPE_SIZE_T
-AC_STRUCT_TM
-
-# Checks for library functions.
-AC_FUNC_STRFTIME
-AC_FUNC_STRERROR_R
-AC_CHECK_HEADERS([sys/utsname.h grp.h pwd.h])
-AC_CHECK_HEADERS([sys/socket.h], [AC_DEFINE([SHIBSP_HAVE_SYS_SOCKET_H],[1],[Define to 1 if you have the <sys/socket> header file.])], [])
-AC_CHECK_FUNCS([strchr strdup strstr timegm gmtime_r localtime_r strtok_r strcasecmp getpwnam getgrnam initgroups])
-AC_CHECK_TYPES([struct sockaddr_storage], [], [], [[#include <sys/socket.h>]])
-AC_CHECK_MEMBERS([struct sockaddr.sa_len], [], [], [[#include <sys/socket.h>]])
-
-AC_CACHE_CHECK([for SOCK_CLOEXEC support], [shib_cv_sock_cloexec],
-[AC_TRY_RUN([
-#include <sys/types.h>
-#include <sys/socket.h>
-int main()
-{
-return socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0) == -1;
-}], [shib_cv_sock_cloexec=yes], [shib_cv_sock_cloexec=no], [shib_cv_sock_cloexec=no])])
-
-if test "$shib_cv_sock_cloexec" = "yes"; then
-	AC_DEFINE([HAVE_SOCK_CLOEXEC], 1, [Define if the SOCK_CLOEXEC flag is supported])
-fi
-
-# checks for pthreads
-ACX_PTHREAD([enable_threads="pthread"],[enable_threads="no"])
-if test $enable_threads != "pthread"; then
-    AC_MSG_ERROR([unable to find pthreads, currently this is required])
-else
-    AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])
-    LIBS="$PTHREAD_LIBS $LIBS"
-    CFLAGS="$PTHREAD_CFLAGS $CFLAGS"
-    CXXFLAGS="$PTHREAD_CFLAGS $CXXFLAGS"
-fi
-
-# OpenSSL settings
-AC_ARG_WITH(openssl,
-    AS_HELP_STRING([--with-openssl=PATH],[where openssl is installed]),
-    [if test x_$with_openssl != x_/usr; then
-        SSLFLAGS="-I${with_openssl}/include"
-    fi])
-
-if test "x$with_openssl" = "x" ; then
-    AC_PATH_PROG(PKG_CONFIG, pkg-config)
-    if test "x$PKG_CONFIG" != x && test "x$PKG_CONFIG" != "xno" ; then
-        if pkg-config openssl ; then
-            SSLFLAGS="`$PKG_CONFIG --cflags openssl`"
-        else
-            AC_MSG_WARN([OpenSSL not supported by pkg-config, try --with-openssl instead])
-        fi
-    fi
-fi
-
-AC_MSG_CHECKING(for OpenSSL cflags)
-AC_MSG_RESULT($SSLFLAGS)
-CPPFLAGS="$SSLFLAGS $CPPFLAGS"
-
-AC_CHECK_HEADER([openssl/x509.h],,AC_MSG_ERROR([unable to find openssl header files]))
-
-AC_LANG([C++])
-
-# C++ requirements
-AC_CXX_NAMESPACES
-AC_CXX_REQUIRE_STL
-
-# Boost
-BOOST_REQUIRE
-BOOST_BIND
-BOOST_LAMBDA
-BOOST_POINTER_CONTAINER
-BOOST_SMART_PTR
-BOOST_STRING_ALGO
-BOOST_TUPLE
-CPPFLAGS="$BOOST_CPPFLAGS $CPPFLAGS"
-
-# Thank you Solaris, really.
-AC_MSG_CHECKING(for ctime_r)
-if test -z "$ac_cv_ctime_args"; then
-    AC_COMPILE_IFELSE(
-        [AC_LANG_PROGRAM([[#include <time.h>]], [[time_t clock; char buf[26]; ctime_r(&clock, buf);]])],
-        [ac_cv_ctime_args=2],[])
-
-    AC_COMPILE_IFELSE(
-        [AC_LANG_PROGRAM([[#include <time.h>]], [[time_t clock; char buf[26]; ctime_r(&clock, buf, 26);]])],
-        [ac_cv_ctime_args=3],[])
-fi
-if test -z "$ac_cv_ctime_args"; then
-    AC_MSG_RESULT(no)
-else
-    if test "$ac_cv_ctime_args" = 2; then
-        AC_DEFINE([HAVE_CTIME_R_2],[1],[Define if ctime_r is present with 2 parameters.])
-    elif test "$ac_cv_ctime_args" = 3; then
-        AC_DEFINE([HAVE_CTIME_R_3],[1],[Define if ctime_r is present with 3 parameters.])
-    fi
-    AC_MSG_RESULT([yes, and it takes $ac_cv_ctime_args arguments])
-fi 
-
-# log4shib settings (favor this version over the log4cpp code)
-AC_PATH_PROG(LOG4SHIB_CONFIG,log4shib-config)
-AC_ARG_WITH(log4shib,
-    AS_HELP_STRING([--with-log4shib=PATH],[where log4shib-config is installed]),
-    [
-    LOG4SHIB_CONFIG="${with_log4shib}"
-    if ! test -f "${LOG4SHIB_CONFIG}"; then
-        LOG4SHIB_CONFIG="${with_log4shib}/bin/log4shib-config"
-    fi
-    ])
-if test -f "${LOG4SHIB_CONFIG}" ; then
-    LIBS="`${LOG4SHIB_CONFIG} --libs` $LIBS"
-    CPPFLAGS="`${LOG4SHIB_CONFIG} --cflags` $CPPFLAGS"
-    AC_CHECK_HEADER([log4shib/CategoryStream.hh],,AC_MSG_ERROR([unable to find log4shib header files]))
-    AC_LINK_IFELSE(
-        [AC_LANG_PROGRAM([[#include <log4shib/Category.hh>
-#include <log4shib/CategoryStream.hh>]],
-            [[log4shib::Category::getInstance("foo").errorStream() << log4shib::eol]])],
-        [AC_DEFINE([SHIBSP_LOG4SHIB],[1],[Define to 1 if log4shib library is used.])],
-        [AC_MSG_ERROR([unable to link with log4shib])])
-else
-    AC_MSG_WARN([log4shib-config not found, may need to use --with-log4shib option])
-    AC_MSG_WARN([will look for original log4cpp library])
-    
-    # log4cpp settings
-    AC_PATH_PROG(LOG4CPP_CONFIG,log4cpp-config)
-    AC_ARG_WITH(log4cpp,
-        AS_HELP_STRING([--with-log4cpp=PATH],[where log4cpp-config is installed]),
-        [
-        LOG4CPP_CONFIG="${with_log4cpp}"
-        if ! test -f "${LOG4CPP_CONFIG}"; then
-            LOG4CPP_CONFIG="${with_log4cpp}/bin/log4cpp-config"
-        fi
-        ])
-    if test -f "${LOG4CPP_CONFIG}"; then
-        AC_MSG_WARN([will try to use log4cpp, note that most non-Internet2 supplied versions are not thread-safe])
-        LIBS="`${LOG4CPP_CONFIG} --libs` $LIBS"
-        CPPFLAGS="`${LOG4CPP_CONFIG} --cflags` $CPPFLAGS"
-        AC_CHECK_HEADER([log4cpp/CategoryStream.hh],,AC_MSG_ERROR([unable to find log4cpp header files]))
-        AC_LINK_IFELSE(
-            [AC_LANG_PROGRAM([[#include <log4cpp/Category.hh>
-#include <log4cpp/CategoryStream.hh>]],
-                [[log4cpp::Category::getInstance("foo").errorStream() << log4cpp::eol]])],
-            [AC_DEFINE([SHIBSP_LOG4CPP],[1],[Define to 1 if log4cpp library is used.])],
-            [AC_MSG_ERROR([unable to link with log4cpp, need version 1.0 or later])])
-    else
-        AC_MSG_ERROR([log4cpp-config not found, may need to use --with-log4cpp option])
-    fi
-fi
-
-# Xerces settings
-AC_ARG_WITH(xerces,
-    AS_HELP_STRING([--with-xerces=PATH],[where xerces-c is installed]),,
-    [with_xerces=/usr])
-if test x_$with_xerces != x_/usr; then
-    CPPFLAGS="-I${with_xerces}/include $CPPFLAGS"
-    LIBS="-L${with_xerces}/lib -lxerces-c $LIBS"
-else
-    LIBS="-lxerces-c $LIBS"
-fi
-
-AC_CHECK_HEADER([xercesc/dom/DOM.hpp],,AC_MSG_ERROR([unable to find xerces header files]))
-AC_MSG_CHECKING([Xerces version])
-AC_PREPROC_IFELSE(
-    [AC_LANG_PROGRAM([#include <xercesc/util/XercesVersion.hpp>],
-[#if  _XERCES_VERSION >= 20700
-int i = 0;
-#else
-#error version 2.7.0 or above required
-#endif])],
-    [AC_MSG_RESULT(OK)],
-    [AC_MSG_FAILURE([Xerces-C v2.7.0 or higher is required, v3.x preferred])])
-AC_LINK_IFELSE(
-    [AC_LANG_PROGRAM([[#include <xercesc/util/PlatformUtils.hpp>]],[[xercesc::XMLPlatformUtils::Initialize()]])],
-    ,[AC_MSG_ERROR([unable to link with Xerces])])
-
-AC_MSG_CHECKING([whether Xerces XMLString::release(XMLByte**) exists])
-AC_COMPILE_IFELSE(
-    [AC_LANG_PROGRAM([[#include <xercesc/util/XMLString.hpp>]],
-    [[using namespace XERCES_CPP_NAMESPACE; XMLByte* buf=NULL; XMLString::release(&buf);]])],
-    [AC_MSG_RESULT([yes])AC_DEFINE([SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE],[1],[Define to 1 if Xerces XMLString includes XMLByte release.])],
-    [AC_MSG_RESULT([no])])
-
-AC_MSG_CHECKING([whether Xerces DOMNodeFilter API returns a short])
-AC_COMPILE_IFELSE(
-    [AC_LANG_PROGRAM([[#include <xercesc/dom/DOM.hpp>]],
-        [[using namespace XERCES_CPP_NAMESPACE;
-      class Blocker : public DOMNodeFilter {
-      public:
-        short acceptNode(const DOMNode* node) const {
-            return FILTER_REJECT;
-        }
-      };
-      static Blocker g_Blocker;
-    ]])],
-    [AC_MSG_RESULT([yes])AC_DEFINE([SHIBSP_XERCESC_SHORT_ACCEPTNODE],[1],[Define to 1 if Xerces DOMNodeFilter API returns a short.])],
-    [AC_MSG_RESULT([no])])
-
-# XML-Security settings
-AC_ARG_WITH(xmlsec,
-    AS_HELP_STRING([--with-xmlsec=PATH],[where xmlsec is installed]),,
-    [with_xmlsec=/usr])
-if test x_$with_xmlsec != x_/usr; then
-    CPPFLAGS="-I${with_xmlsec}/include $CPPFLAGS"
-    XMLSEC_LIBS="-L${with_xmlsec}/lib -lxml-security-c $XMLSEC_LIBS"
-else
-    XMLSEC_LIBS="-lxml-security-c $XMLSEC_LIBS"
-fi
-
-# save and append master libs
-save_LIBS="$LIBS"
-LIBS="$XMLSEC_LIBS $LIBS"
-
-AC_CHECK_HEADER([xsec/utils/XSECPlatformUtils.hpp],,AC_MSG_ERROR([unable to find XML-Security-C header files]))
-AC_MSG_CHECKING([XML-Security-C version])
-AC_PREPROC_IFELSE(
-    [AC_LANG_PROGRAM([#include <xsec/utils/XSECPlatformUtils.hpp>],
-    [#if XSEC_VERSION_MAJOR > 1 || (XSEC_VERSION_MAJOR == 1 && XSEC_VERSION_MEDIUM > 3)
-int i = 0;
-#else
-#error need version 1.4.0 or later
-#endif])],
-    [AC_MSG_RESULT(OK)],
-    [AC_MSG_FAILURE([XML-Security-C version 1.4.0 or greater is required.])])
-AC_LINK_IFELSE(
-    [AC_LANG_PROGRAM([[#include <xsec/utils/XSECPlatformUtils.hpp>]],
-        [[XSECPlatformUtils::Initialise()]])],,
-    [AC_MSG_ERROR([unable to link with XML-Security])])
-
-AC_MSG_CHECKING([whether XML-Security-C supports white/blacklisting of algorithms])
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <xsec/framework/XSECAlgorithmMapper.hpp>]], [[XSECAlgorithmMapper* mapper; mapper->whitelistAlgorithm(NULL);]])],[AC_MSG_RESULT([yes])
-      AC_DEFINE([SHIBSP_XMLSEC_WHITELISTING],[1],[Define to 1 if XML-Security-C supports white/blacklisting algorithms.])],[AC_MSG_RESULT([no])])
-
-# restore master libs
-LIBS="$save_LIBS"
-
-#XML-Tooling settings
-AC_ARG_WITH(xmltooling,
-    AS_HELP_STRING([--with-xmltooling=PATH],[where xmltooling is installed]),,
-    [with_xmltooling=/usr])
-if test x_$with_xmltooling != x_/usr; then
-    CPPFLAGS="-I${with_xmltooling}/include $CPPFLAGS"
-    DX_INCLUDE="${with_xmltooling}/include"
-    LITE_LIBS="-L${with_xmltooling}/lib -lxmltooling-lite"
-    XMLSEC_LIBS="-L${with_xmltooling}/lib -lxmltooling $XMLSEC_LIBS"
-else
-    LITE_LIBS="-lxmltooling-lite"
-    XMLSEC_LIBS="-lxmltooling $XMLSEC_LIBS"
-fi
-
-AC_CHECK_HEADER([xmltooling/base.h],,AC_MSG_ERROR([unable to find xmltooling header files]))
-
-# save and append master libs
-save_LIBS="$LIBS"
-LIBS="$XMLSEC_LIBS $LIBS"
-
-AC_LINK_IFELSE(
-    [AC_LANG_PROGRAM([[#include <xmltooling/XMLToolingConfig.h>
-#include <xmltooling/version.h>]],
-        [[#if _XMLTOOLING_VERSION >= 10500
-xmltooling::XMLToolingConfig::getConfig();
-#else
-#error Need XMLTooling version 1.5 or higher
-#endif]])],
-    ,[AC_MSG_ERROR([unable to link with XMLTooling, or version was too old])])
-
-# restore master libs
-LIBS="$save_LIBS"
-
-# Establish location of xmltooling catalog.
-XMLTOOLINGXMLDIR=""
-if test "x$with_xmltooling" = "x" ; then
-   with_xmltooling="/usr"
-fi
-if test -f $with_xmltooling/share/xml/xmltooling/catalog.xml ; then
-    XMLTOOLINGXMLDIR="$with_xmltooling"
-elif test -f $with_xerces/share/xml/xmltooling/catalog.xml ; then
-    XMLTOOLINGXMLDIR="$with_xerces"
-elif test -f $with_log4shib/share/xml/xmltooling/catalog.xml ; then
-    XMLTOOLINGXMLDIR="$with_log4shib"
-fi
-if test "x$XMLTOOLINGXMLDIR" = "x" ; then
-    AC_MSG_ERROR([xmltooling XML catalog not found, may need to use --with-xmltooling option])
-fi
-XMLTOOLINGXMLDIR="$XMLTOOLINGXMLDIR/share/xml/xmltooling"
-AC_SUBST(XMLTOOLINGXMLDIR)
-
-# OpenSAML settings
-AC_ARG_WITH(saml,
-    AS_HELP_STRING([--with-saml=PATH],[where opensaml is installed]),,
-    [with_saml=/usr])
-if test x_$with_saml != x_/usr; then
-    CPPFLAGS="-I${with_saml}/include $CPPFLAGS"
-    DX_INCLUDE="$DX_INCLUDE ${with_saml}/include"
-    XMLSEC_LIBS="-L${with_saml}/lib -lsaml $XMLSEC_LIBS"
-else
-    XMLSEC_LIBS="-lsaml $XMLSEC_LIBS"
-fi
-
-# save and append master libs
-save_LIBS="$LIBS"
-LIBS="$XMLSEC_LIBS $LIBS"
-
-AC_CHECK_HEADER([saml/saml2/metadata/Metadata.h],,AC_MSG_ERROR([unable to find OpenSAML header files]))
-AC_LINK_IFELSE(
-    [AC_LANG_PROGRAM([[#include <saml/SAMLConfig.h>
-#include <saml/version.h>]],
-[[#if _OPENSAML_VERSION >= 20500
-opensaml::SAMLConfig::getConfig();
-#else
-#error Need OpenSAML version 2.5 or higher
-#endif]])],
-    ,[AC_MSG_ERROR([unable to link with OpenSAML, or version was too old])
-	])
-
-# restore master libs
-LIBS="$save_LIBS"
-
-# Establish location of opensaml catalogs.
-OPENSAMLXMLDIR=""
-if test "x$with_saml" = "x" ; then
-    with_saml="/usr"
-fi
-if test -f $with_saml/share/xml/opensaml/saml20-catalog.xml ; then
-    OPENSAMLXMLDIR="$with_saml"
-elif test -f $with_xmltooling/share/xml/opensaml/saml20-catalog.xml ; then
-    OPENSAMLXMLDIR="$with_xmltooling"
-elif test -f $with_xerces/share/xml/opensaml/saml20-catalog.xml ; then
-    OPENSAMLXMLDIR="$with_xerces"
-elif test -f $with_log4shib/share/xml/opensaml/saml20-catalog.xml ; then
-    OPENSAMLXMLDIR="$with_log4shib"
-fi
-if test "x$OPENSAMLXMLDIR" = "x" ; then
-    AC_MSG_ERROR([opensaml XML catalogs not found, may need to use --with-saml option])
-fi
-OPENSAMLXMLDIR="$OPENSAMLXMLDIR/share/xml/opensaml"
-AC_SUBST(OPENSAMLXMLDIR)
-
-AC_SUBST(LITE_LIBS)
-AC_SUBST(XMLSEC_LIBS)
-
-# output the underlying makefiles
-WANT_SUBDIRS="doc schemas configs shibsp plugins shibd util"
-AC_CONFIG_FILES([Makefile doc/Makefile schemas/Makefile \
-	configs/Makefile shibsp/Makefile plugins/Makefile \
-	shibd/Makefile util/Makefile selinux/Makefile])
-
-## ADFS?
-AC_CONFIG_FILES([adfs/Makefile])
-AC_ARG_ENABLE([adfs],
-    AS_HELP_STRING([--disable-adfs],[don't build the ADFS module]),
-    [adfs_enabled=$enableval], [adfs_enabled=yes])
-if test "x$adfs_enabled" = "x" ; then
-    adfs_enabled=yes
-fi
-AC_MSG_CHECKING(whether to build the ADFS module)
-if test "$adfs_enabled" = "no" ; then
-    AC_MSG_RESULT(no)
-else
-    AC_MSG_RESULT(yes)
-    WANT_SUBDIRS="$WANT_SUBDIRS adfs"
-fi
-
-## systemd
-dnl Systemd will be disabled by default and requires you to run configure with
-dnl --enable-systemd to look for and enable systemd.
-AC_ARG_ENABLE(systemd,
-    AS_HELP_STRING([--enable-systemd],[Build with systemd (Default = no)]),
-	[if test "x$enableval" = "x" ; then
-         WANT_SYSTEMD=no
-	 else
-	     WANT_SYSTEMD="$enableval"
-	 fi
-	],[ WANT_SYSTEMD=no ])
-AC_MSG_CHECKING(whether to build with systemd)
-
-AC_MSG_RESULT($WANT_SYSTEMD)
-if test "$WANT_SYSTEMD" = "yes" ; then
-	AC_CHECK_HEADER([systemd/sd-daemon.h], [
-	    AC_CHECK_LIB([systemd-daemon], [sd_notify], [hassdnotify="y"])])
-	AS_IF([test "x$hassdnotify=" = x], [
-	   AC_MSG_ERROR([Unable to find a suitable libsystemd-daemon library])
-	])
-	AC_DEFINE([HAVE_SD_NOTIFY],[1],[Define to 1 if you have the sd_notify function.])
-	PKG_CHECK_MODULES([SYSTEMD], [libsystemd-daemon])
-	AC_SUBST([SYSTEMD_CFLAGS])
-	AC_SUBST([SYSTEMD_LIBS])
-fi
-
-#
-# Build NSAPI module?
-#
-AC_MSG_CHECKING(for NSAPI module option)
-AC_ARG_WITH(nsapi,
-    AS_HELP_STRING([--with-nsapi=DIR],[Build NSAPI module for Netscape/iPlanet/SunONE]),
-    [WANT_NSAPI=$withval],[WANT_NSAPI=no])
-AC_MSG_RESULT($WANT_NSAPI)
-
-if test "$WANT_NSAPI" != "no"; then
-  if test ! -d $WANT_NSAPI/bin ; then
-    AC_MSG_ERROR([Please specify the path to the root of your Netscape/iPlanet/SunONE server using --with-nsapi=DIR])
-  fi
-  AC_MSG_CHECKING(for NSAPI include files)
-  if test -d $WANT_NSAPI/include ; then
-    NSAPI_INCLUDE=$WANT_NSAPI/include
-    AC_MSG_RESULT(Netscape-Enterprise 3.x style)
-    AC_CHECK_HEADERS([$NSAPI_INCLUDE/nsapi.h],,,[#define XP_UNIX])
-    NSAPI_INCLUDE="$NSAPI_INC_DIR -I$NSAPI_INCLUDE"
-  fi
-  if test -d $WANT_NSAPI/plugins/include ; then
-    test -n "$NSAPI_INCLUDE" && NSAPI_INC_DIR="-I$NSAPI_INCLUDE"
-    NSAPI_INCLUDE="$WANT_NSAPI/plugins/include"
-    AC_MSG_RESULT(iPlanet 4.x / SunONE 6.x style)
-    AC_CHECK_HEADERS([$NSAPI_INCLUDE/nsapi.h],,,[#define XP_UNIX])
-    NSAPI_INCLUDE="$NSAPI_INC_DIR -I$NSAPI_INCLUDE"
-  fi
-  if test "$NSAPI_INCLUDE" = ""; then
-    AC_MSG_ERROR([Please check you have nsapi.h in either $WANT_NSAPI/include or $WANT_NSAPI/plugins/include])
-  fi
-fi
-
-AC_SUBST(NSAPI_INCLUDE)
-
-# always output the Makefile, even if you don't use it
-AC_CONFIG_FILES([nsapi_shib/Makefile])
-AM_CONDITIONAL(BUILD_NSAPI,test ! "$WANT_NSAPI" = "no")
-
-# add the NSAPI module to the list of wanted subdirs..
-if test ! "$WANT_NSAPI" = "no" ; then
-    WANT_SUBDIRS="$WANT_SUBDIRS nsapi_shib"
-fi
-
-
-#
-# Build FastCGI support?
-#
-AC_MSG_CHECKING(for FastCGI support)
-AC_ARG_WITH(fastcgi,
-    AS_HELP_STRING([--with-fastcgi=DIR],[Build FastCGI support]),
-    [WANT_FASTCGI=$withval],[WANT_FASTCGI=no])
-AC_MSG_RESULT($WANT_FASTCGI)
-
-if test "$WANT_FASTCGI" != "no"; then
-
-    if test "$WANT_FASTCGI" != "yes"; then
-        if test x_$WANT_FASTCGI != x_/usr; then
-            FASTCGI_INCLUDE="-I$WANT_FASTCGI/include"
-            FASTCGI_LDFLAGS="-L$WANT_FASTCGI/lib"
-        fi
-    fi
-
-    # save and append master flags
-    save_CPPFLAGS="$CPPFLAGS"
-    CPPFLAGS="$FASTCGI_INCLUDE $CPPFLAGS"
-
-    AC_CHECK_HEADER([fcgio.h],,AC_MSG_ERROR([unable to find FastCGI header files]))
-    FASTCGI_LIBS="-lfcgi -lfcgi++"
-
-    # restore standard flags
-    CPPFLAGS="$save_CPPFLAGS"
-fi
-
-AC_SUBST(FASTCGI_INCLUDE)
-AC_SUBST(FASTCGI_LDFLAGS)
-AC_SUBST(FASTCGI_LIBS)
-
-# always output the Makefile, even if you don't use it
-AC_CONFIG_FILES([fastcgi/Makefile])
-AM_CONDITIONAL(BUILD_FASTCGI,test ! "$WANT_FASTCGI" = "no")
-
-if test ! "$WANT_FASTCGI" = "no" ; then
-    WANT_SUBDIRS="$WANT_SUBDIRS fastcgi"
-fi
-
-#
-# Build Memcached support?
-#
-AC_MSG_CHECKING(for Memcached support)
-AC_ARG_WITH(memcached,
-    AS_HELP_STRING([--with-memcached=DIR],[Build Memcached support]),
-    [WANT_MEMCACHED=$withval],[WANT_MEMCACHED=no])
-AC_MSG_RESULT($WANT_MEMCACHED)
-
-if test "$WANT_MEMCACHED" != "no"; then
-
-    if test "$WANT_MEMCACHED" != "yes"; then
-        if test x_$WANT_MEMCACHED != x_/usr; then
-            MEMCACHED_INCLUDE="-I$WANT_MEMCACHED/include"
-            MEMCACHED_LDFLAGS="-L$WANT_MEMCACHED/lib"
-        fi
-    fi
-
-    # save and append master flags
-    save_CPPFLAGS="$CPPFLAGS"
-    CPPFLAGS="$MEMCACHED_INCLUDE $CPPFLAGS"    
-
-    AC_CHECK_HEADER([libmemcached/memcached.h],,
-        AC_MSG_ERROR([unable to find Memcached header files]))
-    AC_CHECK_DECL([memcached_last_error_message],
-        [AC_DEFINE([HAVE_MEMCACHED_LAST_ERROR_MESSAGE],[1],[Define to 1 if libmemcached supports error handling function.])],,
-        [#include <libmemcached/memcached.h>])
-    MEMCACHED_LIBS="-lmemcached"
-
-    # restore standard flags
-    CPPFLAGS="$save_CPPFLAGS"
-fi
-
-AC_SUBST(MEMCACHED_INCLUDE)
-AC_SUBST(MEMCACHED_LDFLAGS)
-AC_SUBST(MEMCACHED_LIBS)
-
-# always output the Makefile, even if you don't use it
-AC_CONFIG_FILES([memcache-store/Makefile])
-AM_CONDITIONAL(BUILD_MEMCACHED,test ! "$WANT_MEMCACHED" = "no")
-
-if test ! "$WANT_MEMCACHED" = "no" ; then
-    WANT_SUBDIRS="$WANT_SUBDIRS memcache-store"
-fi
-
-
-#
-# If no --enable-apache-xx specified 
-# find a default and fake the specific parameters
-#
-
-# simple macro to peek at an enable or a with
-AC_DEFUN([Peek],
-if test "[${[$1]_][$2]+set}" = set; then
-  peekval="${[$1]_[$2]}"
-  $3
-fi; dnl
-)
-
-AC_MSG_CHECKING(if default apache needed)
-need_default=yes
-Peek(enable,apache_13,need_default=no)
-Peek(enable,apache_20,need_default=no)
-Peek(enable,apache_22,need_default=no)
-Peek(enable,apache_24,need_default=no)
-AC_MSG_RESULT($need_default)
-
-if test "$need_default" = "yes"; then
-  # find an apxs, then the httpd
-  xs=
-  Peek(with,apxs,xs="$peekval")
-  Peek(with,apxs2,xs="$peekval")
-  Peek(with,apxs22,xs="$peekval")
-  Peek(with,apxs24,xs="$peekval")
-  if test "x$xs" = "x"; then
-     AC_PATH_PROGS(xs, apxs2 apxs,
-        AC_MSG_ERROR(No apxs, no Apache found. Try --with-apxs, --with-apxs2, etc.),
-        [/usr/local/apache2/bin:/usr/local/apache/bin:/usr/sbin:$PATH])
-  fi
-  # ask the daemon for the version and set parameters
-  AC_MSG_CHECKING(default apache version)
-  httpd="`$xs -q SBINDIR`/`$xs -q TARGET`"
-  if test "x$httpd" != "x" && test -f $httpd ; then
-     v=`$httpd -v|$SED -n -e 's/.*Apache\/\.*//p'`
-     case $v in
-       1.3*)   [enable_apache_13]=yes
-               [with_apxs]=$xs
-               AC_MSG_RESULT(1.3)
-               ;;
-       2.0*)   [enable_apache_20]=yes
-               [with_apxs2]=$xs
-               AC_MSG_RESULT(2.0)
-               ;;
-       2.2*)   [enable_apache_22]=yes
-               [with_apxs22]=$xs
-               AC_MSG_RESULT(2.2)
-               ;;
-       2.4*)   [enable_apache_24]=yes
-               [with_apxs24]=$xs
-               AC_MSG_RESULT(2.4)
-               ;;
-       *)      AC_MSG_ERROR(unusable Apache versions: $v. Try setting --with-apxs, --with=apxs2, etc.)
-     esac
-  else 
-     AC_MSG_RESULT(cannot determine Apache version. Try setting --with-apxs, --with-apxs2, etc.)
-  fi
-fi
-
-# Apache 1.3 (mod_shib_13)
-#   --enable-apache-13
-#   --with-apxs      (DSO build, the normal way, uses apxs to derive build flags)
-
-AC_ARG_ENABLE(apache-13,
-	AS_HELP_STRING([--enable-apache-13],[enable the Apache 1.3 module]),
-	[if test "x$enableval" = "x" ; then
-         WANT_APACHE_13=yes
-	 else
-	     WANT_APACHE_13="$enableval"
-	 fi
-	],[ WANT_APACHE_13=no ])
-AC_MSG_CHECKING(whether to build Apache 1.3 module)
-if test "$WANT_APACHE_13" != yes && test "$WANT_APACHE_13" != no ; then
-   WANT_APACHE_13=yes
-fi
-AC_MSG_RESULT($WANT_APACHE_13)
-
-if test "$WANT_APACHE_13" = "yes" ; then
-    AC_ARG_WITH(apxs, 
-        AS_HELP_STRING([--with-apxs=FILE],[Specifies where to find the Apache 1.3 apxs script.]),
-        [
-        AC_MSG_CHECKING(for user-specified apxs name/location)
-        if test "$withval" != "no" ; then
-          if test "$withval" != "yes"; then
-            APXS=$withval
-            AC_MSG_RESULT("$withval")
-          fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APXS, apxs, no)
-        if test "$APXS" = "no" ; then
-          for i in /usr/sbin /usr/local/apache/bin ; do
-            if test "$APXS" = "no" && test -f "$i/apxs"; then
-              APXS="$i/apxs"
-            fi
-          done
-        fi
-        ])
-
-    AC_MSG_CHECKING([to see if apxs was located])
-    if test ! -f "$APXS" ; then
-        AC_MSG_RESULT(no)
-        AC_MSG_ERROR([Unable to locate apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs option.])
-    fi
-    AC_MSG_RESULT($APXS)
-    AC_SUBST(APXS)
-
-    # extract settings we need from APXS -q
-    APXS_CC="`$APXS -q CC`"
-    APXS_CFLAGS="`$APXS -q CFLAGS` `$APXS -q CFLAGS_SHLIB`"
-    APXS_INCLUDE="`$APXS -q INCLUDEDIR`"
-fi
-
-AC_SUBST(APXS_CFLAGS)
-AC_SUBST(APXS_INCLUDE)
-
-
-# Apache 2.0 (mod_shib_20)
-#   --enable-apache-20
-#   --with-apxs2      (DSO build, the normal way, uses apxs to derive build flags)
-#   --with-apr        (DSO build, APR development package installed separately)
-#   --with-apu        (DSO build, APR-UTIL development package installed separately)
-
-AC_ARG_ENABLE(apache-20,
-	AS_HELP_STRING([--enable-apache-20],[enable the Apache 2.0 module]),
-	[if test "x$enableval" = "x" ; then
-         WANT_APACHE_20=yes
-	 else
-	     WANT_APACHE_20="$enableval"
-	 fi
-	],[ WANT_APACHE_20=no ])
-AC_MSG_CHECKING(whether to build Apache 2.0 module)
-if test "$WANT_APACHE_20" != yes && test "$WANT_APACHE_20" != no ; then
-    WANT_APACHE_20=yes
-fi
-AC_MSG_RESULT($WANT_APACHE_20)
-
-if test "$WANT_APACHE_20" = "yes" ; then
-    AC_ARG_WITH(apxs2, 
-        AS_HELP_STRING([--with-apxs2=FILE],[Specifies where to find the Apache 2.0 apxs script.]),
-        [
-        AC_MSG_CHECKING(for user-specified Apache 2.0 apxs name/location)
-        if test "$withval" != "no" ; then
-          if test "$withval" != "yes"; then
-            APXS2=$withval
-            AC_MSG_RESULT("$withval")
-          fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APXS2, apxs2, no)
-        if test "$APXS2" = "no" ; then
-            AC_PATH_PROG(APXS2, apxs, no)
-        fi
-        if test "$APXS2" = "no" ; then
-          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-            if test "$APXS2" = "no" && test -f "$i/apxs2" ; then
-              APXS2="$i/apxs2"
-            fi
-          done
-          if test "$APXS2" = "no" ; then
-            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-              if test "$APXS2" = "no" && test -f "$i/apxs" ; then
-                APXS2="$i/apxs"
-              fi
-            done
-          fi
-        fi
-        ])
-
-    AC_MSG_CHECKING([to see if Apache 2.0 apxs was located])
-    if test ! -f "$APXS2" ; then
-        AC_MSG_RESULT(no)
-        AC_MSG_ERROR([Unable to locate Apache 2.0 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs2 option.])
-    fi
-    AC_MSG_RESULT($APXS2)
-    AC_SUBST(APXS2)
-
-    # APR settings
-    AC_ARG_WITH(apr, 
-        AS_HELP_STRING([--with-apr=PATH],[where apr-config is installed]),
-        [
-        AC_MSG_CHECKING(for user-specified apr-config name/location)
-        if test "$withval" != "no" ; then
-            if test "$withval" != "yes"; then
-                APR_CONFIG=$withval
-                AC_MSG_RESULT("$withval")
-            fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APR_CONFIG, apr-config,,[`$APXS2 -q SBINDIR`]:[$PATH])
-        ])
-	if test -f "${APR_CONFIG}"; then
-        APR_CFLAGS="`${APR_CONFIG} --cflags` `${APR_CONFIG} --cppflags` `${APR_CONFIG} --includes`"
-    else
-        AC_MSG_ERROR([Unable to locate apr-config, may need --with-apr option.])
-    fi
-
-    # APU settings
-    AC_ARG_WITH(apu, 
-        AS_HELP_STRING([--with-apu=PATH],[where apu-config is installed]),
-        [
-        AC_MSG_CHECKING(for user-specified apu-config name/location)
-        if test "$withval" != "no" ; then
-            if test "$withval" != "yes"; then
-                APU_CONFIG=$withval
-                AC_MSG_RESULT("$withval")
-            fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APU_CONFIG, apu-config,,[`$APXS2 -q SBINDIR`]:[$PATH])
-        ])
-    if test -f "${APU_CONFIG}"; then
-        APU_CFLAGS="`${APU_CONFIG} --includes`"
-    else
-        AC_MSG_ERROR([Unable to locate apu-config, may need --with-apu option.])
-    fi
-
-    # extract settings we need from APXS2 -q
-    APXS2_CC="`$APXS2 -q CC`"
-    APXS2_CFLAGS="`$APXS2 -q CPPFLAGS` `$APXS2 -q CFLAGS` $APR_CFLAGS $APU_CFLAGS"
-    APXS2_INCLUDE="`$APXS2 -q INCLUDEDIR`"
-fi
-
-AC_SUBST(APXS2_CFLAGS)
-AC_SUBST(APXS2_INCLUDE)
-
-
-# Apache 2.2 (mod_shib_22)
-#   --enable-apache-22
-#   --with-apxs22     (DSO build, the normal way, uses apxs to derive build flags)
-#   --with-apr1       (DSO build, APR development package installed separately)
-#   --with-apu1       (DSO build, APR-UTIL development package installed separately)
-
-AC_ARG_ENABLE(apache-22,
-	AS_HELP_STRING([--enable-apache-22],[enable the Apache 2.2 module]),
-	[if test "x$enableval" = "x" ; then
-         WANT_APACHE_22=yes
-	 else
-	     WANT_APACHE_22="$enableval"
-	 fi
-	],[ WANT_APACHE_22=no ])
-AC_MSG_CHECKING(whether to build Apache 2.2 module)
-if test "$WANT_APACHE_22" != yes && test "$WANT_APACHE_22" != no ; then
-    WANT_APACHE_22=yes
-fi
-AC_MSG_RESULT($WANT_APACHE_22)
-
-if test "$WANT_APACHE_22" = "yes" ; then
-    AC_ARG_WITH(apxs22, 
-        AS_HELP_STRING([--with-apxs22=FILE],[Specifies where to find the Apache 2.2 apxs script.]),
-        [
-        AC_MSG_CHECKING(for user-specified Apache 2.2 apxs name/location)
-        if test "$withval" != "no" ; then
-          if test "$withval" != "yes"; then
-            APXS22=$withval
-            AC_MSG_RESULT("$withval")
-          fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APXS22, apxs2, no)
-        if test "$APXS22" = "no" ; then
-            AC_PATH_PROG(APXS22, apxs, no)
-        fi
-        if test "$APXS22" = "no" ; then
-          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-            if test "$APXS22" = "no" && test -f "$i/apxs2" ; then
-              APXS22="$i/apxs2"
-            fi
-          done
-          if test "$APXS22" = "no" ; then
-            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-              if test "$APXS22" = "no" && test -f "$i/apxs" ; then
-                APXS22="$i/apxs"
-              fi
-            done
-          fi
-        fi
-        ])
-
-    AC_MSG_CHECKING([to see if Apache 2.2 apxs was located])
-    if test ! -f "$APXS22" ; then
-        AC_MSG_RESULT(no)
-        AC_MSG_ERROR([Unable to locate Apache 2.2 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs22 option.])
-    fi
-    AC_MSG_RESULT($APXS22)
-    AC_SUBST(APXS22)
-
-    # APR1 settings
-    AC_ARG_WITH(apr1, 
-        AS_HELP_STRING([--with-apr1=PATH],[where apr-1-config is installed]),
-        [
-        AC_MSG_CHECKING(for user-specified apr-1-config name/location)
-        if test "$withval" != "no" ; then
-            if test "$withval" != "yes"; then
-                APR1_CONFIG=$withval
-                AC_MSG_RESULT("$withval")
-            fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APR1_CONFIG, apr-1-config,,[`$APXS22 -q SBINDIR`]:[$PATH])
-        ])
-	if test -f "${APR1_CONFIG}"; then
-        APR1_CFLAGS="`${APR1_CONFIG} --cflags` `${APR1_CONFIG} --cppflags` `${APR1_CONFIG} --includes`"
-    else
-        AC_MSG_ERROR([Unable to locate apr-1-config, may need --with-apr1 option.])
-    fi
-
-    # APU1 settings
-    AC_ARG_WITH(apu1, 
-        AS_HELP_STRING([--with-apu1=PATH],[where apu-1-config is installed]),
-        [
-        AC_MSG_CHECKING(for user-specified apu-1-config name/location)
-        if test "$withval" != "no" ; then
-            if test "$withval" != "yes"; then
-                APU1_CONFIG=$withval
-                AC_MSG_RESULT("$withval")
-            fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APU1_CONFIG, apu-1-config,,[`$APXS22 -q SBINDIR`]:[$PATH])
-        ])
-    if test -f "${APU1_CONFIG}"; then
-        APU1_CFLAGS="`${APU1_CONFIG} --includes`"
-    else
-        AC_MSG_ERROR([Unable to locate apu-1-config, may need --with-apu1 option.])
-    fi
-
-    # extract settings we need from APXS22 -q
-    APXS22_CC="`$APXS22 -q CC`"
-    APXS22_CFLAGS="`$APXS22 -q CPPFLAGS` `$APXS22 -q CFLAGS` $APR1_CFLAGS $APU1_CFLAGS"
-    APXS22_INCLUDE="`$APXS22 -q INCLUDEDIR`"
-fi
-
-AC_SUBST(APXS22_CFLAGS)
-AC_SUBST(APXS22_INCLUDE)
-
-# Apache 2.4 (mod_shib_24)
-#   --enable-apache-24
-#   --with-apxs24     (DSO build, the normal way, uses apxs to derive build flags)
-#   --with-apr1       (DSO build, APR development package installed separately)
-#   --with-apu1       (DSO build, APR-UTIL development package installed separately)
-
-AC_ARG_ENABLE(apache-24,
-	AS_HELP_STRING([--enable-apache-24],[enable the Apache 2.4 module]),
-	[if test "x$enableval" = "x" ; then
-         WANT_APACHE_24=yes
-	 else
-	     WANT_APACHE_24="$enableval"
-	 fi
-	],[ WANT_APACHE_24=no ])
-AC_MSG_CHECKING(whether to build Apache 2.4 module)
-if test "$WANT_APACHE_24" != yes && test "$WANT_APACHE_24" != no ; then
-    WANT_APACHE_24=yes
-fi
-AC_MSG_RESULT($WANT_APACHE_24)
-
-if test "$WANT_APACHE_24" = "yes" ; then
-    AC_ARG_WITH(apxs24, 
-        AS_HELP_STRING([--with-apxs24=FILE],[Specifies where to find the Apache 2.4 apxs script.]),
-        [
-        AC_MSG_CHECKING(for user-specified Apache 2.4 apxs name/location)
-        if test "$withval" != "no" ; then
-          if test "$withval" != "yes"; then
-            APXS24=$withval
-            AC_MSG_RESULT("$withval")
-          fi
-        fi
-        ],
-        [
-        AC_PATH_PROG(APXS24, apxs2, no)
-        if test "$APXS24" = "no" ; then
-            AC_PATH_PROG(APXS24, apxs, no)
-        fi
-        if test "$APXS24" = "no" ; then
-          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-            if test "$APXS24" = "no" && test -f "$i/apxs2" ; then
-              APXS24="$i/apxs2"
-            fi
-          done
-          if test "$APXS24" = "no" ; then
-            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
-              if test "$APXS24" = "no" && test -f "$i/apxs" ; then
-                APXS24="$i/apxs"
-              fi
-            done
-          fi
-        fi
-        ])
-
-    AC_MSG_CHECKING([to see if Apache 2.4 apxs was located])
-    if test ! -f "$APXS24" ; then
-        AC_MSG_RESULT(no)
-        AC_MSG_ERROR([Unable to locate Apache 2.4 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs24 option.])
-    fi
-    AC_MSG_RESULT($APXS24)
-    AC_SUBST(APXS24)
-
-    # If we haven't done this work already for Apache 2.2
-    if test "$WANT_APACHE_22" != "yes" ; then
-        # APR1 settings
-        AC_ARG_WITH(apr1,
-            AS_HELP_STRING([--with-apr1=PATH],[where apr-1-config is installed]),
-            [
-            AC_MSG_CHECKING(for user-specified apr-1-config name/location)
-            if test "$withval" != "no" ; then
-                if test "$withval" != "yes"; then
-                    APR1_CONFIG=$withval
-                    AC_MSG_RESULT("$withval")
-                fi
-            fi
-            ],
-            [
-            AC_PATH_PROG(APR1_CONFIG, apr-1-config,,[`$APXS24 -q SBINDIR`]:[$PATH])
-            ])
-        if test -f "${APR1_CONFIG}"; then
-            APR1_CFLAGS="`${APR1_CONFIG} --cflags` `${APR1_CONFIG} --cppflags` `${APR1_CONFIG} --includes`"
-        else
-            AC_MSG_ERROR([Unable to locate apr-1-config, may need --with-apr1 option.])
-        fi
-
-        # APU1 settings
-        AC_ARG_WITH(apu1,
-            AS_HELP_STRING([--with-apu1=PATH],[where apu-1-config is installed]),
-            [
-            AC_MSG_CHECKING(for user-specified apu-1-config name/location)
-            if test "$withval" != "no" ; then
-                if test "$withval" != "yes"; then
-                    APU1_CONFIG=$withval
-                    AC_MSG_RESULT("$withval")
-                fi
-            fi
-            ],
-            [
-            AC_PATH_PROG(APU1_CONFIG, apu-1-config,,[`$APXS24 -q SBINDIR`]:[$PATH])
-            ])
-        if test -f "${APU1_CONFIG}"; then
-            APU1_CFLAGS="`${APU1_CONFIG} --includes`"
-        else
-            AC_MSG_ERROR([Unable to locate apu-1-config, may need --with-apu1 option.])
-        fi
-    fi
-    
-    # extract settings we need from APXS24 -q
-    APXS24_CC="`$APXS24 -q CC`"
-    APXS24_CFLAGS="`$APXS24 -q CPPFLAGS` `$APXS24 -q CFLAGS` $APR1_CFLAGS $APU1_CFLAGS"
-    APXS24_INCLUDE="`$APXS24 -q INCLUDEDIR`"
-fi
-
-AC_SUBST(APXS24_CFLAGS)
-AC_SUBST(APXS24_INCLUDE)
-
-# always output the Makefile, even if you don't use it
-AC_CONFIG_FILES([apache/Makefile])
-AM_CONDITIONAL(BUILD_AP13,test "$WANT_APACHE_13" = "yes")
-AM_CONDITIONAL(BUILD_AP20,test "$WANT_APACHE_20" = "yes")
-AM_CONDITIONAL(BUILD_AP22,test "$WANT_APACHE_22" = "yes")
-AM_CONDITIONAL(BUILD_AP24,test "$WANT_APACHE_24" = "yes")
-
-# add the apache module to the list of wanted subdirs..
-if test "$WANT_APACHE_13" = "yes" || test "$WANT_APACHE_20" = "yes" || test "$WANT_APACHE_22" = "yes" || test "$WANT_APACHE_24" = "yes" ; then
-    WANT_SUBDIRS="$WANT_SUBDIRS apache"
-fi
-
-
-#
-# Implement the checks of the ODBC Storage Service
-#
-# 1) Assume the user wants ODBC; if it's not found then just continue without
-# 2) If the user specifically requested odbc, look for it and ERROR if not found
-# 3) If the user specifically requested no odbc, don't build it.
-#
-
-AC_CONFIG_FILES([odbc-store/Makefile])
-
-# determine whether we should enable the odbc ccache
-AC_ARG_ENABLE([odbc],
-	AS_HELP_STRING([--disable-odbc],[disable the ODBC Storage Service]),
-	[odbc_enabled=$enableval], [odbc_enabled=default])
-if test "x$odbc_enabled" = "x" ; then
-    odbc_enabled=yes
-fi
-
-# Are we trying to build ODBC?
-AC_MSG_CHECKING(whether to build the ODBC storage service)
-if test "$odbc_enabled" = "yes" ; then
-    build_odbc=yes
-    AC_MSG_RESULT(yes)
-elif test "$odbc_enabled" = "default" ; then
-    build_odbc=yes
-    AC_MSG_RESULT([yes, if it can be found])
-else
-    build_odbc=no
-    AC_MSG_RESULT(no)
-fi
-
-# If we're trying to build ODBC, try to find the odbc_config program.
-if test "$build_odbc" = "yes" ; then
-    odbc_dir=""
-    AC_ARG_WITH(odbc,
-	   AS_HELP_STRING([--with-odbc=PATH],[directory where odbc is installed]),
-	    [if test "$with_odbc" = no ; then
-            AC_MSG_ERROR([Try running --disable-odbc instead.])
-         elif test "$with_odbc" != yes ; then
-            odbc_dir="$with_odbc/bin"
-            if test "$with_odbc" != /usr ; then
-                ODBC_CFLAGS="-I$with_odbc/include"
-                ODBC_LIBS="-L$with_odbc/lib"
-            fi
-         fi])
-
-   AC_PATH_PROG(ODBC_CONFIG, odbc_config, no, $odbc_dir $PATH )
-   if test "$ODBC_CONFIG" = no ; then
-      AC_MSG_WARN([Cannot find odbc_config, will try to guess settings.])
-      ODBC_LIBS="$ODBC_LIBS -lodbc"
-   else
-      ODBC_CFLAGS=`$ODBC_CONFIG --cflags`
-      ODBC_LIBS=`$ODBC_CONFIG --libs`
-   fi
-
-   save_CPPFLAGS="$CPPFLAGS"
-   CPPFLAGS="$CPPFLAGS $ODBC_CFLAGS"
-
-   AC_CHECK_HEADER([sql.h], [have_sql_h=yes], [have_sql_h=no])
-   if test "$have_sql_h" = no -a "$odbc_enabled" = "yes" ; then
-     AC_MSG_ERROR(unable to find ODBC header files)
-   fi
-
-   if test "$have_sql_h" = yes ; then
-      save_LIBS="$LIBS"
-      LIBS="$LIBS $ODBC_LIBS"
-      AC_MSG_CHECKING(if we can link againt ODBC)
-      AC_LINK_IFELSE(
-        [AC_LANG_PROGRAM([[#include <sql.h>
- #include <sqlext.h>
- #include <stdio.h>]],
-            [[SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, (void*)SQL_CP_ONE_PER_HENV, 0)]])],
-        [have_odbc_libs=yes],[have_odbc_libs=no])
-      LIBS="$save_LIBS"
-      if test "$have_odbc_libs" = no ; then
-         if test "$odbc_enabled" = "yes" ; then
-            AC_MSG_ERROR([unable to link with ODBC Library])
-         else
-            AC_MSG_RESULT([no, skipping ODBC])
-         fi
-      fi
-   fi
-
-   CPPFLAGS="$save_CPPFLAGS"
-fi
-
-# if have_odbc_libs=yes then go ahead with building ODBC
-if test "$have_odbc_libs" = yes ; then
-   # this AC_MSG_RESULT is from above!
-   AC_MSG_RESULT(yes)
-   WANT_SUBDIRS="$WANT_SUBDIRS odbc-store"
-   AC_SUBST(ODBC_CFLAGS)
-   AC_SUBST(ODBC_LIBS)
-fi
-
-# GSS-API checking
-
-GSSAPI_ROOT="/usr"
-AC_ARG_WITH(gssapi-includes,
-  AS_HELP_STRING([--with-gssapi-includes=DIR],[Specify location of GSSAPI header]),
-  [ GSSAPI_INCS="-I$withval"
-    want_gss="yes" ]
-)
-
-AC_ARG_WITH(gssapi-libs,
-  AS_HELP_STRING([--with-gssapi-libs=DIR],[Specify location of GSSAPI libs]),
-  [ GSSAPI_LIB_DIR="-L$withval"
-    want_gss="yes" ]
-)
-
-AC_ARG_WITH(gssapi,
-  AS_HELP_STRING([--with-gssapi=DIR],[Where to look for GSSAPI]),
-  [ GSSAPI_ROOT="$withval"
-  if test x"$GSSAPI_ROOT" != xno; then
-    want_gss="yes"
-    if test x"$GSSAPI_ROOT" = xyes; then
-      dnl if yes, then use default root
-      GSSAPI_ROOT="/usr"
-    fi
-  fi
-])
-
-save_CPPFLAGS="$CPPFLAGS"
-AC_MSG_CHECKING([if GSSAPI support is requested])
-if test x"$want_gss" = xyes; then
-  AC_MSG_RESULT(yes)
-
-  if test -z "$GSSAPI_INCS"; then
-     if test -f "$GSSAPI_ROOT/bin/krb5-config"; then
-        GSSAPI_INCS=`$GSSAPI_ROOT/bin/krb5-config --cflags gssapi`
-     elif test "$GSSAPI_ROOT" != "yes"; then
-        GSSAPI_INCS="-I$GSSAPI_ROOT/include"
-     fi
-  fi
-
-  CPPFLAGS="$CPPFLAGS $GSSAPI_INCS"
-
-  AC_CHECK_HEADER(gss.h,
-    [
-      dnl found in the given dirs
-      AC_DEFINE([SHIBSP_HAVE_GSSGNU],[1],[if you have the GNU gssapi libraries])
-      gnu_gss=yes
-    ],
-    [
-      dnl not found, check Heimdal or MIT
-      AC_CHECK_HEADERS([gssapi/gssapi.h], [], [not_mit=1])
-      AC_CHECK_HEADERS(
-        [gssapi/gssapi_generic.h gssapi/gssapi_krb5.h],
-        [],
-        [not_mit=1],
-        [
-AC_INCLUDES_DEFAULT
-#ifdef HAVE_GSSAPI_GSSAPI_H
-#include <gssapi/gssapi.h>
-#endif
-        ])
-      if test "x$not_mit" = "x1"; then
-        dnl MIT not found, check for Heimdal
-        AC_CHECK_HEADER([gssapi.h],
-            [
-              dnl found
-              AC_DEFINE([SHIBSP_HAVE_GSSHEIMDAL],[1],[if you have the Heimdal gssapi libraries])
-            ],
-            [
-              dnl no header found, disabling GSS
-              want_gss=no
-              AC_MSG_WARN([disabling GSSAPI since no header files was found])
-            ]
-          )
-      else
-        dnl MIT found
-        AC_DEFINE([SHIBSP_HAVE_GSSMIT],[1],[if you have the MIT gssapi libraries])
-        dnl check if we have a really old MIT kerberos (<= 1.2)
-        AC_MSG_CHECKING([if gssapi headers declare GSS_C_NT_HOSTBASED_SERVICE])
-        AC_COMPILE_IFELSE([
-          AC_LANG_PROGRAM([[
-#include <gssapi/gssapi.h>
-#include <gssapi/gssapi_generic.h>
-#include <gssapi/gssapi_krb5.h>
-          ]],[[
-            gss_import_name(
-                            (OM_uint32 *)0,
-                            (gss_buffer_t)0,
-                            GSS_C_NT_HOSTBASED_SERVICE,
-                            (gss_name_t *)0);
-          ]])
-        ],[
-          AC_MSG_RESULT([yes])
-        ],[
-          AC_MSG_RESULT([no])
-          AC_DEFINE([HAVE_OLD_GSSMIT],[1],[if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE])
-        ])
-      fi
-    ]
-  )
-else
-  AC_MSG_RESULT(no)
-fi
-if test x"$want_gss" = xyes; then
-  AC_DEFINE([SHIBSP_HAVE_GSSAPI],[1],[if you have the gssapi libraries])
-
-  if test -n "$gnu_gss"; then
-    LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR"
-    LIBS="$LIBS -lgss"
-  else
-    if test -z "$GSSAPI_LIB_DIR"; then
-      GSSAPI_LIB_DIR="$GSSAPI_ROOT/lib$libsuff"
-    fi
-    if test "$GSSAPI_ROOT" != "yes"; then
-       LDFLAGS="$LDFLAGS -L$GSSAPI_ROOT/lib$libsuff"
-    fi
-    if test -f "$GSSAPI_ROOT/bin/krb5-config"; then
-      dnl krb5-config doesn't have --libs-only-L or similar, put everything
-      dnl into LIBS
-      gss_libs=`$GSSAPI_ROOT/bin/krb5-config --libs gssapi`
-    else
-      if test "x$not_mit" = "x1"; then
-        gss_libs="-lgssapi"
-      else
-        gss_libs="-lgssapi_krb5"
-      fi
-    fi
-    LIBS="$LIBS $gss_libs"
-  fi
-
-  AC_MSG_CHECKING([whether GSS-API naming extensions are available])
-  AC_COMPILE_IFELSE(
-    [AC_LANG_PROGRAM([[
-#ifdef SHIBSP_HAVE_GSSGNU
-# include <gss.h>
-#elif defined SHIBSP_HAVE_GSSMIT
-# include <gssapi/gssapi.h>
-# include <gssapi/gssapi_ext.h>
-#else
-# include <gssapi.h>
-#endif]],
-    [[gss_get_name_attribute(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);]])],
-    [AC_MSG_RESULT([yes])AC_DEFINE([HAVE_GSSAPI_NAMINGEXTS],[1],[Define to 1 if GSS-API naming extensions are available.])],
-    [AC_MSG_RESULT([no])])
-
-  AC_MSG_CHECKING([whether GSS-API composite name import is available])
-  AC_COMPILE_IFELSE(
-    [AC_LANG_PROGRAM([[
-#ifdef SHIBSP_HAVE_GSSGNU
-# include <gss.h>
-#elif defined SHIBSP_HAVE_GSSMIT
-# include <gssapi/gssapi.h>
-# include <gssapi/gssapi_ext.h>
-#else
-# include <gssapi.h>
-#endif]],
-    [[
-    OM_uint32 minor;
-    gss_name_t srcname;
-    gss_buffer_desc importbuf;
-    gss_import_name(&minor, &importbuf, GSS_C_NT_EXPORT_NAME_COMPOSITE, &srcname);
-    ]])],
-    [AC_MSG_RESULT([yes])AC_DEFINE([HAVE_GSSAPI_COMPOSITE_NAME],[1],[Define to 1 if GSS-API composite name import is available.])],
-    [AC_MSG_RESULT([no])])
-    
-else
-  CPPFLAGS="$save_CPPFLAGS"
-fi
-
-
-AC_SUBST(WANT_SUBDIRS)
-
-if test -n "$APXS_CC" && test "$APXS_CC" != "$CC" ; then
-  echo "=================================================================="
-  echo "WARNING: You have chosen to compile Apache-1.3 modules with a different"
-  echo "         compiler than the one used to compile Apache."
-  echo ""
-  echo "    Current compiler:      $CC"
-  echo "   Apache's compiler:      $APXS_CC"
-  echo ""
-  echo "This could cause problems."
-  echo "=================================================================="
-fi
-
-if test -n "$APXS2_CC" && test "$APXS2_CC" != "$CC" ; then
-  echo "=================================================================="
-  echo "WARNING: You have chosen to compile Apache-2.0 modules with a different"
-  echo "         compiler than the one used to compile Apache."
-  echo ""
-  echo "    Current compiler:      $CC"
-  echo "   Apache's compiler:      $APXS2_CC"
-  echo ""
-  echo "This could cause problems."
-  echo "=================================================================="
-fi
-
-if test -n "$APXS22_CC" && test "$APXS22_CC" != "$CC" ; then
-  echo "=================================================================="
-  echo "WARNING: You have chosen to compile Apache-2.2 modules with a different"
-  echo "         compiler than the one used to compile Apache."
-  echo ""
-  echo "    Current compiler:      $CC"
-  echo "   Apache's compiler:      $APXS22_CC"
-  echo ""
-  echo "This could cause problems."
-  echo "=================================================================="
-fi
-
-if test -n "$APXS24_CC" && test "$APXS24_CC" != "$CC" ; then
-  echo "=================================================================="
-  echo "WARNING: You have chosen to compile Apache-2.4 modules with a different"
-  echo "         compiler than the one used to compile Apache."
-  echo ""
-  echo "    Current compiler:      $CC"
-  echo "   Apache's compiler:      $APXS24_CC"
-  echo ""
-  echo "This could cause problems."
-  echo "=================================================================="
-fi
-
-LIBTOOL="$LIBTOOL --silent"
-
-AC_OUTPUT
+AC_PREREQ([2.50])
+AC_INIT([shibboleth],[2.5.6],[https://issues.shibboleth.net/],[shibboleth-sp])
+AC_CONFIG_SRCDIR(shibsp)
+AC_CONFIG_AUX_DIR(build-aux)
+AC_CONFIG_MACRO_DIR(m4)
+AM_INIT_AUTOMAKE
+AC_DISABLE_STATIC
+AC_PROG_LIBTOOL
+
+# Docygen features
+DX_HTML_FEATURE(ON)
+DX_CHM_FEATURE(OFF)
+DX_CHI_FEATURE(OFF)
+DX_MAN_FEATURE(OFF)
+DX_RTF_FEATURE(OFF)
+DX_XML_FEATURE(OFF)
+DX_PDF_FEATURE(OFF)
+DX_PS_FEATURE(OFF)
+DX_INIT_DOXYGEN(shibboleth, doxygen.cfg, doc/api)
+DX_INCLUDE=
+
+AC_ARG_ENABLE(debug,
+    AS_HELP_STRING([--enable-debug],[Have GCC compile with symbols (Default = no)]),
+    enable_debug=$enableval, enable_debug=no)
+
+if test "$enable_debug" = "yes" ; then
+    GCC_CFLAGS="$CFLAGS -g -D_DEBUG"
+    GCC_CXXFLAGS="$CXXFLAGS -g -D_DEBUG"
+else
+    GCC_CFLAGS="$CFLAGS -O2 -DNDEBUG"
+    GCC_CXXFLAGS="$CXXFLAGS -O2 -DNDEBUG"
+fi
+
+AC_CONFIG_HEADERS([config.h shibsp/config_pub.h])
+AC_CONFIG_FILES([shibboleth.spec])
+
+AC_PROG_CC([gcc gcc3 cc])
+AC_PROG_CXX([g++ g++3 c++ CC])
+AC_CANONICAL_HOST
+
+if test "$GCC" = "yes" ; then
+#    AC_HAVE_GCC_VERSION(4,0,0,0,
+#        [
+#        AC_DEFINE(GCC_HASCLASSVISIBILITY,1,
+#            [Define to enable class visibility control in gcc.])
+#        GCC_CFLAGS="$GCC_CFLAGS -fvisibility=hidden -fvisibility-inlines-hidden"
+#        GCC_CXXFLAGS="$GCC_CXXFLAGS -fvisibility=hidden -fvisibility-inlines-hidden"
+#        ])
+    CFLAGS="-Wall $GCC_CFLAGS"
+    CXXFLAGS="-Wall $GCC_CXXFLAGS"
+fi
+
+# Fix for Sun Workshop compiler in debug mode, may be Sun case #6360993
+# Also enables POSIX semantics for some functions.
+case "${host_cpu}-${host_os}" in
+    *solaris*)
+	CFLAGS="$CFLAGS -D_POSIX_PTHREAD_SEMANTICS"
+	CXXFLAGS="$CXXFLAGS -D_POSIX_PTHREAD_SEMANTICS"
+	if test "$CXX" = "CC" ; then
+		CXXFLAGS="$CXXFLAGS -Qoption ccfe -stabs=no%dfltlit+no%dflthlp"
+	fi
+    ;;
+	*osf*)
+	CXXFLAGS="$CXXFLAGS -D_POSIX_PII_SOCKET"
+	;;
+esac
+
+AC_LANG(C)
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_TYPE_SIZE_T
+AC_STRUCT_TM
+
+# Checks for library functions.
+AC_FUNC_STRFTIME
+AC_FUNC_STRERROR_R
+AC_CHECK_HEADERS([sys/utsname.h grp.h pwd.h])
+AC_CHECK_HEADERS([sys/socket.h], [AC_DEFINE([SHIBSP_HAVE_SYS_SOCKET_H],[1],[Define to 1 if you have the <sys/socket> header file.])], [])
+AC_CHECK_FUNCS([strchr strdup strstr timegm gmtime_r localtime_r strtok_r strcasecmp getpwnam getgrnam initgroups])
+AC_CHECK_TYPES([struct sockaddr_storage], [], [], [[#include <sys/socket.h>]])
+AC_CHECK_MEMBERS([struct sockaddr.sa_len], [], [], [[#include <sys/socket.h>]])
+
+AC_CACHE_CHECK([for SOCK_CLOEXEC support], [shib_cv_sock_cloexec],
+[AC_TRY_RUN([
+#include <sys/types.h>
+#include <sys/socket.h>
+int main()
+{
+return socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0) == -1;
+}], [shib_cv_sock_cloexec=yes], [shib_cv_sock_cloexec=no], [shib_cv_sock_cloexec=no])])
+
+if test "$shib_cv_sock_cloexec" = "yes"; then
+	AC_DEFINE([HAVE_SOCK_CLOEXEC], 1, [Define if the SOCK_CLOEXEC flag is supported])
+fi
+
+# checks for pthreads
+ACX_PTHREAD([enable_threads="pthread"],[enable_threads="no"])
+if test $enable_threads != "pthread"; then
+    AC_MSG_ERROR([unable to find pthreads, currently this is required])
+else
+    AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])
+    LIBS="$PTHREAD_LIBS $LIBS"
+    CFLAGS="$PTHREAD_CFLAGS $CFLAGS"
+    CXXFLAGS="$PTHREAD_CFLAGS $CXXFLAGS"
+fi
+
+# OpenSSL settings
+AC_ARG_WITH(openssl,
+    AS_HELP_STRING([--with-openssl=PATH],[where openssl is installed]),
+    [if test x_$with_openssl != x_/usr; then
+        SSLFLAGS="-I${with_openssl}/include"
+    fi])
+
+if test "x$with_openssl" = "x" ; then
+    AC_PATH_PROG(PKG_CONFIG, pkg-config)
+    if test "x$PKG_CONFIG" != x && test "x$PKG_CONFIG" != "xno" ; then
+        if pkg-config openssl ; then
+            SSLFLAGS="`$PKG_CONFIG --cflags openssl`"
+        else
+            AC_MSG_WARN([OpenSSL not supported by pkg-config, try --with-openssl instead])
+        fi
+    fi
+fi
+
+AC_MSG_CHECKING(for OpenSSL cflags)
+AC_MSG_RESULT($SSLFLAGS)
+CPPFLAGS="$SSLFLAGS $CPPFLAGS"
+
+AC_CHECK_HEADER([openssl/x509.h],,AC_MSG_ERROR([unable to find openssl header files]))
+
+AC_LANG([C++])
+
+# C++ requirements
+AC_CXX_NAMESPACES
+AC_CXX_REQUIRE_STL
+
+# Boost
+BOOST_REQUIRE
+BOOST_BIND
+BOOST_LAMBDA
+BOOST_POINTER_CONTAINER
+BOOST_SMART_PTR
+BOOST_STRING_ALGO
+BOOST_TUPLE
+CPPFLAGS="$BOOST_CPPFLAGS $CPPFLAGS"
+
+# Thank you Solaris, really.
+AC_MSG_CHECKING(for ctime_r)
+if test -z "$ac_cv_ctime_args"; then
+    AC_COMPILE_IFELSE(
+        [AC_LANG_PROGRAM([[#include <time.h>]], [[time_t clock; char buf[26]; ctime_r(&clock, buf);]])],
+        [ac_cv_ctime_args=2],[])
+
+    AC_COMPILE_IFELSE(
+        [AC_LANG_PROGRAM([[#include <time.h>]], [[time_t clock; char buf[26]; ctime_r(&clock, buf, 26);]])],
+        [ac_cv_ctime_args=3],[])
+fi
+if test -z "$ac_cv_ctime_args"; then
+    AC_MSG_RESULT(no)
+else
+    if test "$ac_cv_ctime_args" = 2; then
+        AC_DEFINE([HAVE_CTIME_R_2],[1],[Define if ctime_r is present with 2 parameters.])
+    elif test "$ac_cv_ctime_args" = 3; then
+        AC_DEFINE([HAVE_CTIME_R_3],[1],[Define if ctime_r is present with 3 parameters.])
+    fi
+    AC_MSG_RESULT([yes, and it takes $ac_cv_ctime_args arguments])
+fi 
+
+# log4shib settings (favor this version over the log4cpp code)
+AC_PATH_PROG(LOG4SHIB_CONFIG,log4shib-config)
+AC_ARG_WITH(log4shib,
+    AS_HELP_STRING([--with-log4shib=PATH],[where log4shib-config is installed]),
+    [
+    LOG4SHIB_CONFIG="${with_log4shib}"
+    if ! test -f "${LOG4SHIB_CONFIG}"; then
+        LOG4SHIB_CONFIG="${with_log4shib}/bin/log4shib-config"
+    fi
+    ])
+if test -f "${LOG4SHIB_CONFIG}" ; then
+    LIBS="`${LOG4SHIB_CONFIG} --libs` $LIBS"
+    CPPFLAGS="`${LOG4SHIB_CONFIG} --cflags` $CPPFLAGS"
+    AC_CHECK_HEADER([log4shib/CategoryStream.hh],,AC_MSG_ERROR([unable to find log4shib header files]))
+    AC_LINK_IFELSE(
+        [AC_LANG_PROGRAM([[#include <log4shib/Category.hh>
+#include <log4shib/CategoryStream.hh>]],
+            [[log4shib::Category::getInstance("foo").errorStream() << log4shib::eol]])],
+        [AC_DEFINE([SHIBSP_LOG4SHIB],[1],[Define to 1 if log4shib library is used.])],
+        [AC_MSG_ERROR([unable to link with log4shib])])
+else
+    AC_MSG_WARN([log4shib-config not found, may need to use --with-log4shib option])
+    AC_MSG_WARN([will look for original log4cpp library])
+    
+    # log4cpp settings
+    AC_PATH_PROG(LOG4CPP_CONFIG,log4cpp-config)
+    AC_ARG_WITH(log4cpp,
+        AS_HELP_STRING([--with-log4cpp=PATH],[where log4cpp-config is installed]),
+        [
+        LOG4CPP_CONFIG="${with_log4cpp}"
+        if ! test -f "${LOG4CPP_CONFIG}"; then
+            LOG4CPP_CONFIG="${with_log4cpp}/bin/log4cpp-config"
+        fi
+        ])
+    if test -f "${LOG4CPP_CONFIG}"; then
+        AC_MSG_WARN([will try to use log4cpp, note that most non-Internet2 supplied versions are not thread-safe])
+        LIBS="`${LOG4CPP_CONFIG} --libs` $LIBS"
+        CPPFLAGS="`${LOG4CPP_CONFIG} --cflags` $CPPFLAGS"
+        AC_CHECK_HEADER([log4cpp/CategoryStream.hh],,AC_MSG_ERROR([unable to find log4cpp header files]))
+        AC_LINK_IFELSE(
+            [AC_LANG_PROGRAM([[#include <log4cpp/Category.hh>
+#include <log4cpp/CategoryStream.hh>]],
+                [[log4cpp::Category::getInstance("foo").errorStream() << log4cpp::eol]])],
+            [AC_DEFINE([SHIBSP_LOG4CPP],[1],[Define to 1 if log4cpp library is used.])],
+            [AC_MSG_ERROR([unable to link with log4cpp, need version 1.0 or later])])
+    else
+        AC_MSG_ERROR([log4cpp-config not found, may need to use --with-log4cpp option])
+    fi
+fi
+
+# Xerces settings
+AC_ARG_WITH(xerces,
+    AS_HELP_STRING([--with-xerces=PATH],[where xerces-c is installed]),,
+    [with_xerces=/usr])
+if test x_$with_xerces != x_/usr; then
+    CPPFLAGS="-I${with_xerces}/include $CPPFLAGS"
+    LIBS="-L${with_xerces}/lib -lxerces-c $LIBS"
+else
+    LIBS="-lxerces-c $LIBS"
+fi
+
+AC_CHECK_HEADER([xercesc/dom/DOM.hpp],,AC_MSG_ERROR([unable to find xerces header files]))
+AC_MSG_CHECKING([Xerces version])
+AC_PREPROC_IFELSE(
+    [AC_LANG_PROGRAM([#include <xercesc/util/XercesVersion.hpp>],
+[#if  _XERCES_VERSION >= 20700
+int i = 0;
+#else
+#error version 2.7.0 or above required
+#endif])],
+    [AC_MSG_RESULT(OK)],
+    [AC_MSG_FAILURE([Xerces-C v2.7.0 or higher is required, v3.x preferred])])
+AC_LINK_IFELSE(
+    [AC_LANG_PROGRAM([[#include <xercesc/util/PlatformUtils.hpp>]],[[xercesc::XMLPlatformUtils::Initialize()]])],
+    ,[AC_MSG_ERROR([unable to link with Xerces])])
+
+AC_MSG_CHECKING([whether Xerces XMLString::release(XMLByte**) exists])
+AC_COMPILE_IFELSE(
+    [AC_LANG_PROGRAM([[#include <xercesc/util/XMLString.hpp>]],
+    [[using namespace XERCES_CPP_NAMESPACE; XMLByte* buf=NULL; XMLString::release(&buf);]])],
+    [AC_MSG_RESULT([yes])AC_DEFINE([SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE],[1],[Define to 1 if Xerces XMLString includes XMLByte release.])],
+    [AC_MSG_RESULT([no])])
+
+AC_MSG_CHECKING([whether Xerces DOMNodeFilter API returns a short])
+AC_COMPILE_IFELSE(
+    [AC_LANG_PROGRAM([[#include <xercesc/dom/DOM.hpp>]],
+        [[using namespace XERCES_CPP_NAMESPACE;
+      class Blocker : public DOMNodeFilter {
+      public:
+        short acceptNode(const DOMNode* node) const {
+            return FILTER_REJECT;
+        }
+      };
+      static Blocker g_Blocker;
+    ]])],
+    [AC_MSG_RESULT([yes])AC_DEFINE([SHIBSP_XERCESC_SHORT_ACCEPTNODE],[1],[Define to 1 if Xerces DOMNodeFilter API returns a short.])],
+    [AC_MSG_RESULT([no])])
+
+# XML-Security settings
+AC_ARG_WITH(xmlsec,
+    AS_HELP_STRING([--with-xmlsec=PATH],[where xmlsec is installed]),,
+    [with_xmlsec=/usr])
+if test x_$with_xmlsec != x_/usr; then
+    CPPFLAGS="-I${with_xmlsec}/include $CPPFLAGS"
+    XMLSEC_LIBS="-L${with_xmlsec}/lib -lxml-security-c $XMLSEC_LIBS"
+else
+    XMLSEC_LIBS="-lxml-security-c $XMLSEC_LIBS"
+fi
+
+# save and append master libs
+save_LIBS="$LIBS"
+LIBS="$XMLSEC_LIBS $LIBS"
+
+AC_CHECK_HEADER([xsec/utils/XSECPlatformUtils.hpp],,AC_MSG_ERROR([unable to find XML-Security-C header files]))
+AC_MSG_CHECKING([XML-Security-C version])
+AC_PREPROC_IFELSE(
+    [AC_LANG_PROGRAM([#include <xsec/utils/XSECPlatformUtils.hpp>],
+    [#if XSEC_VERSION_MAJOR > 1 || (XSEC_VERSION_MAJOR == 1 && XSEC_VERSION_MEDIUM > 3)
+int i = 0;
+#else
+#error need version 1.4.0 or later
+#endif])],
+    [AC_MSG_RESULT(OK)],
+    [AC_MSG_FAILURE([XML-Security-C version 1.4.0 or greater is required.])])
+AC_LINK_IFELSE(
+    [AC_LANG_PROGRAM([[#include <xsec/utils/XSECPlatformUtils.hpp>]],
+        [[XSECPlatformUtils::Initialise()]])],,
+    [AC_MSG_ERROR([unable to link with XML-Security])])
+
+AC_MSG_CHECKING([whether XML-Security-C supports white/blacklisting of algorithms])
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <xsec/framework/XSECAlgorithmMapper.hpp>]], [[XSECAlgorithmMapper* mapper; mapper->whitelistAlgorithm(NULL);]])],[AC_MSG_RESULT([yes])
+      AC_DEFINE([SHIBSP_XMLSEC_WHITELISTING],[1],[Define to 1 if XML-Security-C supports white/blacklisting algorithms.])],[AC_MSG_RESULT([no])])
+
+# restore master libs
+LIBS="$save_LIBS"
+
+#XML-Tooling settings
+AC_ARG_WITH(xmltooling,
+    AS_HELP_STRING([--with-xmltooling=PATH],[where xmltooling is installed]),,
+    [with_xmltooling=/usr])
+if test x_$with_xmltooling != x_/usr; then
+    CPPFLAGS="-I${with_xmltooling}/include $CPPFLAGS"
+    DX_INCLUDE="${with_xmltooling}/include"
+    LITE_LIBS="-L${with_xmltooling}/lib -lxmltooling-lite"
+    XMLSEC_LIBS="-L${with_xmltooling}/lib -lxmltooling $XMLSEC_LIBS"
+else
+    LITE_LIBS="-lxmltooling-lite"
+    XMLSEC_LIBS="-lxmltooling $XMLSEC_LIBS"
+fi
+
+AC_CHECK_HEADER([xmltooling/base.h],,AC_MSG_ERROR([unable to find xmltooling header files]))
+
+# save and append master libs
+save_LIBS="$LIBS"
+LIBS="$XMLSEC_LIBS $LIBS"
+
+AC_LINK_IFELSE(
+    [AC_LANG_PROGRAM([[#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/version.h>]],
+        [[#if _XMLTOOLING_VERSION >= 10500
+xmltooling::XMLToolingConfig::getConfig();
+#else
+#error Need XMLTooling version 1.5 or higher
+#endif]])],
+    ,[AC_MSG_ERROR([unable to link with XMLTooling, or version was too old])])
+
+# restore master libs
+LIBS="$save_LIBS"
+
+# Establish location of xmltooling catalog.
+XMLTOOLINGXMLDIR=""
+if test "x$with_xmltooling" = "x" ; then
+   with_xmltooling="/usr"
+fi
+if test -f $with_xmltooling/share/xml/xmltooling/catalog.xml ; then
+    XMLTOOLINGXMLDIR="$with_xmltooling"
+elif test -f $with_xerces/share/xml/xmltooling/catalog.xml ; then
+    XMLTOOLINGXMLDIR="$with_xerces"
+elif test -f $with_log4shib/share/xml/xmltooling/catalog.xml ; then
+    XMLTOOLINGXMLDIR="$with_log4shib"
+fi
+if test "x$XMLTOOLINGXMLDIR" = "x" ; then
+    AC_MSG_ERROR([xmltooling XML catalog not found, may need to use --with-xmltooling option])
+fi
+XMLTOOLINGXMLDIR="$XMLTOOLINGXMLDIR/share/xml/xmltooling"
+AC_SUBST(XMLTOOLINGXMLDIR)
+
+# OpenSAML settings
+AC_ARG_WITH(saml,
+    AS_HELP_STRING([--with-saml=PATH],[where opensaml is installed]),,
+    [with_saml=/usr])
+if test x_$with_saml != x_/usr; then
+    CPPFLAGS="-I${with_saml}/include $CPPFLAGS"
+    DX_INCLUDE="$DX_INCLUDE ${with_saml}/include"
+    XMLSEC_LIBS="-L${with_saml}/lib -lsaml $XMLSEC_LIBS"
+else
+    XMLSEC_LIBS="-lsaml $XMLSEC_LIBS"
+fi
+
+# save and append master libs
+save_LIBS="$LIBS"
+LIBS="$XMLSEC_LIBS $LIBS"
+
+AC_CHECK_HEADER([saml/saml2/metadata/Metadata.h],,AC_MSG_ERROR([unable to find OpenSAML header files]))
+AC_LINK_IFELSE(
+    [AC_LANG_PROGRAM([[#include <saml/SAMLConfig.h>
+#include <saml/version.h>]],
+[[#if _OPENSAML_VERSION >= 20500
+opensaml::SAMLConfig::getConfig();
+#else
+#error Need OpenSAML version 2.5 or higher
+#endif]])],
+    ,[AC_MSG_ERROR([unable to link with OpenSAML, or version was too old])
+	])
+
+# restore master libs
+LIBS="$save_LIBS"
+
+# Establish location of opensaml catalogs.
+OPENSAMLXMLDIR=""
+if test "x$with_saml" = "x" ; then
+    with_saml="/usr"
+fi
+if test -f $with_saml/share/xml/opensaml/saml20-catalog.xml ; then
+    OPENSAMLXMLDIR="$with_saml"
+elif test -f $with_xmltooling/share/xml/opensaml/saml20-catalog.xml ; then
+    OPENSAMLXMLDIR="$with_xmltooling"
+elif test -f $with_xerces/share/xml/opensaml/saml20-catalog.xml ; then
+    OPENSAMLXMLDIR="$with_xerces"
+elif test -f $with_log4shib/share/xml/opensaml/saml20-catalog.xml ; then
+    OPENSAMLXMLDIR="$with_log4shib"
+fi
+if test "x$OPENSAMLXMLDIR" = "x" ; then
+    AC_MSG_ERROR([opensaml XML catalogs not found, may need to use --with-saml option])
+fi
+OPENSAMLXMLDIR="$OPENSAMLXMLDIR/share/xml/opensaml"
+AC_SUBST(OPENSAMLXMLDIR)
+
+AC_SUBST(LITE_LIBS)
+AC_SUBST(XMLSEC_LIBS)
+
+# output the underlying makefiles
+WANT_SUBDIRS="doc schemas configs shibsp plugins shibd util"
+AC_CONFIG_FILES([Makefile doc/Makefile schemas/Makefile \
+	configs/Makefile shibsp/Makefile plugins/Makefile \
+	shibd/Makefile util/Makefile selinux/Makefile])
+
+## ADFS?
+AC_CONFIG_FILES([adfs/Makefile])
+AC_ARG_ENABLE([adfs],
+    AS_HELP_STRING([--disable-adfs],[don't build the ADFS module]),
+    [adfs_enabled=$enableval], [adfs_enabled=yes])
+if test "x$adfs_enabled" = "x" ; then
+    adfs_enabled=yes
+fi
+AC_MSG_CHECKING(whether to build the ADFS module)
+if test "$adfs_enabled" = "no" ; then
+    AC_MSG_RESULT(no)
+else
+    AC_MSG_RESULT(yes)
+    WANT_SUBDIRS="$WANT_SUBDIRS adfs"
+fi
+
+## systemd
+dnl Systemd will be disabled by default and requires you to run configure with
+dnl --enable-systemd to look for and enable systemd.
+AC_ARG_ENABLE(systemd,
+    AS_HELP_STRING([--enable-systemd],[Build with systemd (Default = no)]),
+	[if test "x$enableval" = "x" ; then
+         WANT_SYSTEMD=no
+	 else
+	     WANT_SYSTEMD="$enableval"
+	 fi
+	],[ WANT_SYSTEMD=no ])
+AC_MSG_CHECKING(whether to build with systemd)
+
+AC_MSG_RESULT($WANT_SYSTEMD)
+if test "$WANT_SYSTEMD" = "yes" ; then
+	AC_CHECK_HEADER([systemd/sd-daemon.h], [
+	    AC_CHECK_LIB([systemd-daemon], [sd_notify], [hassdnotify="y"])])
+	AS_IF([test "x$hassdnotify=" = x], [
+	   AC_MSG_ERROR([Unable to find a suitable libsystemd-daemon library])
+	])
+	AC_DEFINE([HAVE_SD_NOTIFY],[1],[Define to 1 if you have the sd_notify function.])
+	PKG_CHECK_MODULES([SYSTEMD], [libsystemd-daemon])
+	AC_SUBST([SYSTEMD_CFLAGS])
+	AC_SUBST([SYSTEMD_LIBS])
+fi
+
+#
+# Build NSAPI module?
+#
+AC_MSG_CHECKING(for NSAPI module option)
+AC_ARG_WITH(nsapi,
+    AS_HELP_STRING([--with-nsapi=DIR],[Build NSAPI module for Netscape/iPlanet/SunONE]),
+    [WANT_NSAPI=$withval],[WANT_NSAPI=no])
+AC_MSG_RESULT($WANT_NSAPI)
+
+if test "$WANT_NSAPI" != "no"; then
+  if test ! -d $WANT_NSAPI/bin ; then
+    AC_MSG_ERROR([Please specify the path to the root of your Netscape/iPlanet/SunONE server using --with-nsapi=DIR])
+  fi
+  AC_MSG_CHECKING(for NSAPI include files)
+  if test -d $WANT_NSAPI/include ; then
+    NSAPI_INCLUDE=$WANT_NSAPI/include
+    AC_MSG_RESULT(Netscape-Enterprise 3.x style)
+    AC_CHECK_HEADERS([$NSAPI_INCLUDE/nsapi.h],,,[#define XP_UNIX])
+    NSAPI_INCLUDE="$NSAPI_INC_DIR -I$NSAPI_INCLUDE"
+  fi
+  if test -d $WANT_NSAPI/plugins/include ; then
+    test -n "$NSAPI_INCLUDE" && NSAPI_INC_DIR="-I$NSAPI_INCLUDE"
+    NSAPI_INCLUDE="$WANT_NSAPI/plugins/include"
+    AC_MSG_RESULT(iPlanet 4.x / SunONE 6.x style)
+    AC_CHECK_HEADERS([$NSAPI_INCLUDE/nsapi.h],,,[#define XP_UNIX])
+    NSAPI_INCLUDE="$NSAPI_INC_DIR -I$NSAPI_INCLUDE"
+  fi
+  if test "$NSAPI_INCLUDE" = ""; then
+    AC_MSG_ERROR([Please check you have nsapi.h in either $WANT_NSAPI/include or $WANT_NSAPI/plugins/include])
+  fi
+fi
+
+AC_SUBST(NSAPI_INCLUDE)
+
+# always output the Makefile, even if you don't use it
+AC_CONFIG_FILES([nsapi_shib/Makefile])
+AM_CONDITIONAL(BUILD_NSAPI,test ! "$WANT_NSAPI" = "no")
+
+# add the NSAPI module to the list of wanted subdirs..
+if test ! "$WANT_NSAPI" = "no" ; then
+    WANT_SUBDIRS="$WANT_SUBDIRS nsapi_shib"
+fi
+
+
+#
+# Build FastCGI support?
+#
+AC_MSG_CHECKING(for FastCGI support)
+AC_ARG_WITH(fastcgi,
+    AS_HELP_STRING([--with-fastcgi=DIR],[Build FastCGI support]),
+    [WANT_FASTCGI=$withval],[WANT_FASTCGI=no])
+AC_MSG_RESULT($WANT_FASTCGI)
+
+if test "$WANT_FASTCGI" != "no"; then
+
+    if test "$WANT_FASTCGI" != "yes"; then
+        if test x_$WANT_FASTCGI != x_/usr; then
+            FASTCGI_INCLUDE="-I$WANT_FASTCGI/include"
+            FASTCGI_LDFLAGS="-L$WANT_FASTCGI/lib"
+        fi
+    fi
+
+    # save and append master flags
+    save_CPPFLAGS="$CPPFLAGS"
+    CPPFLAGS="$FASTCGI_INCLUDE $CPPFLAGS"
+
+    AC_CHECK_HEADER([fcgio.h],,AC_MSG_ERROR([unable to find FastCGI header files]))
+    FASTCGI_LIBS="-lfcgi -lfcgi++"
+
+    # restore standard flags
+    CPPFLAGS="$save_CPPFLAGS"
+fi
+
+AC_SUBST(FASTCGI_INCLUDE)
+AC_SUBST(FASTCGI_LDFLAGS)
+AC_SUBST(FASTCGI_LIBS)
+
+# always output the Makefile, even if you don't use it
+AC_CONFIG_FILES([fastcgi/Makefile])
+AM_CONDITIONAL(BUILD_FASTCGI,test ! "$WANT_FASTCGI" = "no")
+
+if test ! "$WANT_FASTCGI" = "no" ; then
+    WANT_SUBDIRS="$WANT_SUBDIRS fastcgi"
+fi
+
+#
+# Build Memcached support?
+#
+AC_MSG_CHECKING(for Memcached support)
+AC_ARG_WITH(memcached,
+    AS_HELP_STRING([--with-memcached=DIR],[Build Memcached support]),
+    [WANT_MEMCACHED=$withval],[WANT_MEMCACHED=no])
+AC_MSG_RESULT($WANT_MEMCACHED)
+
+if test "$WANT_MEMCACHED" != "no"; then
+
+    if test "$WANT_MEMCACHED" != "yes"; then
+        if test x_$WANT_MEMCACHED != x_/usr; then
+            MEMCACHED_INCLUDE="-I$WANT_MEMCACHED/include"
+            MEMCACHED_LDFLAGS="-L$WANT_MEMCACHED/lib"
+        fi
+    fi
+
+    # save and append master flags
+    save_CPPFLAGS="$CPPFLAGS"
+    CPPFLAGS="$MEMCACHED_INCLUDE $CPPFLAGS"    
+
+    AC_CHECK_HEADER([libmemcached/memcached.h],,
+        AC_MSG_ERROR([unable to find Memcached header files]))
+    AC_CHECK_DECL([memcached_last_error_message],
+        [AC_DEFINE([HAVE_MEMCACHED_LAST_ERROR_MESSAGE],[1],[Define to 1 if libmemcached supports error handling function.])],,
+        [#include <libmemcached/memcached.h>])
+    MEMCACHED_LIBS="-lmemcached"
+
+    # restore standard flags
+    CPPFLAGS="$save_CPPFLAGS"
+fi
+
+AC_SUBST(MEMCACHED_INCLUDE)
+AC_SUBST(MEMCACHED_LDFLAGS)
+AC_SUBST(MEMCACHED_LIBS)
+
+# always output the Makefile, even if you don't use it
+AC_CONFIG_FILES([memcache-store/Makefile])
+AM_CONDITIONAL(BUILD_MEMCACHED,test ! "$WANT_MEMCACHED" = "no")
+
+if test ! "$WANT_MEMCACHED" = "no" ; then
+    WANT_SUBDIRS="$WANT_SUBDIRS memcache-store"
+fi
+
+
+#
+# If no --enable-apache-xx specified 
+# find a default and fake the specific parameters
+#
+
+# simple macro to peek at an enable or a with
+AC_DEFUN([Peek],
+if test "[${[$1]_][$2]+set}" = set; then
+  peekval="${[$1]_[$2]}"
+  $3
+fi; dnl
+)
+
+AC_MSG_CHECKING(if default apache needed)
+need_default=yes
+Peek(enable,apache_13,need_default=no)
+Peek(enable,apache_20,need_default=no)
+Peek(enable,apache_22,need_default=no)
+Peek(enable,apache_24,need_default=no)
+AC_MSG_RESULT($need_default)
+
+if test "$need_default" = "yes"; then
+  # find an apxs, then the httpd
+  xs=
+  Peek(with,apxs,xs="$peekval")
+  Peek(with,apxs2,xs="$peekval")
+  Peek(with,apxs22,xs="$peekval")
+  Peek(with,apxs24,xs="$peekval")
+  if test "x$xs" = "x"; then
+     AC_PATH_PROGS(xs, apxs2 apxs,
+        AC_MSG_ERROR(No apxs, no Apache found. Try --with-apxs, --with-apxs2, etc.),
+        [/usr/local/apache2/bin:/usr/local/apache/bin:/usr/sbin:$PATH])
+  fi
+  # ask the daemon for the version and set parameters
+  AC_MSG_CHECKING(default apache version)
+  httpd="`$xs -q SBINDIR`/`$xs -q TARGET`"
+  if test "x$httpd" != "x" && test -f $httpd ; then
+     v=`$httpd -v|$SED -n -e 's/.*Apache\/\.*//p'`
+     case $v in
+       1.3*)   [enable_apache_13]=yes
+               [with_apxs]=$xs
+               AC_MSG_RESULT(1.3)
+               ;;
+       2.0*)   [enable_apache_20]=yes
+               [with_apxs2]=$xs
+               AC_MSG_RESULT(2.0)
+               ;;
+       2.2*)   [enable_apache_22]=yes
+               [with_apxs22]=$xs
+               AC_MSG_RESULT(2.2)
+               ;;
+       2.4*)   [enable_apache_24]=yes
+               [with_apxs24]=$xs
+               AC_MSG_RESULT(2.4)
+               ;;
+       *)      AC_MSG_ERROR(unusable Apache versions: $v. Try setting --with-apxs, --with=apxs2, etc.)
+     esac
+  else 
+     AC_MSG_RESULT(cannot determine Apache version. Try setting --with-apxs, --with-apxs2, etc.)
+  fi
+fi
+
+# Apache 1.3 (mod_shib_13)
+#   --enable-apache-13
+#   --with-apxs      (DSO build, the normal way, uses apxs to derive build flags)
+
+AC_ARG_ENABLE(apache-13,
+	AS_HELP_STRING([--enable-apache-13],[enable the Apache 1.3 module]),
+	[if test "x$enableval" = "x" ; then
+         WANT_APACHE_13=yes
+	 else
+	     WANT_APACHE_13="$enableval"
+	 fi
+	],[ WANT_APACHE_13=no ])
+AC_MSG_CHECKING(whether to build Apache 1.3 module)
+if test "$WANT_APACHE_13" != yes && test "$WANT_APACHE_13" != no ; then
+   WANT_APACHE_13=yes
+fi
+AC_MSG_RESULT($WANT_APACHE_13)
+
+if test "$WANT_APACHE_13" = "yes" ; then
+    AC_ARG_WITH(apxs, 
+        AS_HELP_STRING([--with-apxs=FILE],[Specifies where to find the Apache 1.3 apxs script.]),
+        [
+        AC_MSG_CHECKING(for user-specified apxs name/location)
+        if test "$withval" != "no" ; then
+          if test "$withval" != "yes"; then
+            APXS=$withval
+            AC_MSG_RESULT("$withval")
+          fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APXS, apxs, no)
+        if test "$APXS" = "no" ; then
+          for i in /usr/sbin /usr/local/apache/bin ; do
+            if test "$APXS" = "no" && test -f "$i/apxs"; then
+              APXS="$i/apxs"
+            fi
+          done
+        fi
+        ])
+
+    AC_MSG_CHECKING([to see if apxs was located])
+    if test ! -f "$APXS" ; then
+        AC_MSG_RESULT(no)
+        AC_MSG_ERROR([Unable to locate apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs option.])
+    fi
+    AC_MSG_RESULT($APXS)
+    AC_SUBST(APXS)
+
+    # extract settings we need from APXS -q
+    APXS_CC="`$APXS -q CC`"
+    APXS_CFLAGS="`$APXS -q CFLAGS` `$APXS -q CFLAGS_SHLIB`"
+    APXS_INCLUDE="`$APXS -q INCLUDEDIR`"
+fi
+
+AC_SUBST(APXS_CFLAGS)
+AC_SUBST(APXS_INCLUDE)
+
+
+# Apache 2.0 (mod_shib_20)
+#   --enable-apache-20
+#   --with-apxs2      (DSO build, the normal way, uses apxs to derive build flags)
+#   --with-apr        (DSO build, APR development package installed separately)
+#   --with-apu        (DSO build, APR-UTIL development package installed separately)
+
+AC_ARG_ENABLE(apache-20,
+	AS_HELP_STRING([--enable-apache-20],[enable the Apache 2.0 module]),
+	[if test "x$enableval" = "x" ; then
+         WANT_APACHE_20=yes
+	 else
+	     WANT_APACHE_20="$enableval"
+	 fi
+	],[ WANT_APACHE_20=no ])
+AC_MSG_CHECKING(whether to build Apache 2.0 module)
+if test "$WANT_APACHE_20" != yes && test "$WANT_APACHE_20" != no ; then
+    WANT_APACHE_20=yes
+fi
+AC_MSG_RESULT($WANT_APACHE_20)
+
+if test "$WANT_APACHE_20" = "yes" ; then
+    AC_ARG_WITH(apxs2, 
+        AS_HELP_STRING([--with-apxs2=FILE],[Specifies where to find the Apache 2.0 apxs script.]),
+        [
+        AC_MSG_CHECKING(for user-specified Apache 2.0 apxs name/location)
+        if test "$withval" != "no" ; then
+          if test "$withval" != "yes"; then
+            APXS2=$withval
+            AC_MSG_RESULT("$withval")
+          fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APXS2, apxs2, no)
+        if test "$APXS2" = "no" ; then
+            AC_PATH_PROG(APXS2, apxs, no)
+        fi
+        if test "$APXS2" = "no" ; then
+          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+            if test "$APXS2" = "no" && test -f "$i/apxs2" ; then
+              APXS2="$i/apxs2"
+            fi
+          done
+          if test "$APXS2" = "no" ; then
+            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+              if test "$APXS2" = "no" && test -f "$i/apxs" ; then
+                APXS2="$i/apxs"
+              fi
+            done
+          fi
+        fi
+        ])
+
+    AC_MSG_CHECKING([to see if Apache 2.0 apxs was located])
+    if test ! -f "$APXS2" ; then
+        AC_MSG_RESULT(no)
+        AC_MSG_ERROR([Unable to locate Apache 2.0 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs2 option.])
+    fi
+    AC_MSG_RESULT($APXS2)
+    AC_SUBST(APXS2)
+
+    # APR settings
+    AC_ARG_WITH(apr, 
+        AS_HELP_STRING([--with-apr=PATH],[where apr-config is installed]),
+        [
+        AC_MSG_CHECKING(for user-specified apr-config name/location)
+        if test "$withval" != "no" ; then
+            if test "$withval" != "yes"; then
+                APR_CONFIG=$withval
+                AC_MSG_RESULT("$withval")
+            fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APR_CONFIG, apr-config,,[`$APXS2 -q SBINDIR`]:[$PATH])
+        ])
+	if test -f "${APR_CONFIG}"; then
+        APR_CFLAGS="`${APR_CONFIG} --cflags` `${APR_CONFIG} --cppflags` `${APR_CONFIG} --includes`"
+    else
+        AC_MSG_ERROR([Unable to locate apr-config, may need --with-apr option.])
+    fi
+
+    # APU settings
+    AC_ARG_WITH(apu, 
+        AS_HELP_STRING([--with-apu=PATH],[where apu-config is installed]),
+        [
+        AC_MSG_CHECKING(for user-specified apu-config name/location)
+        if test "$withval" != "no" ; then
+            if test "$withval" != "yes"; then
+                APU_CONFIG=$withval
+                AC_MSG_RESULT("$withval")
+            fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APU_CONFIG, apu-config,,[`$APXS2 -q SBINDIR`]:[$PATH])
+        ])
+    if test -f "${APU_CONFIG}"; then
+        APU_CFLAGS="`${APU_CONFIG} --includes`"
+    else
+        AC_MSG_ERROR([Unable to locate apu-config, may need --with-apu option.])
+    fi
+
+    # extract settings we need from APXS2 -q
+    APXS2_CC="`$APXS2 -q CC`"
+    APXS2_CFLAGS="`$APXS2 -q CPPFLAGS` `$APXS2 -q CFLAGS` $APR_CFLAGS $APU_CFLAGS"
+    APXS2_INCLUDE="`$APXS2 -q INCLUDEDIR`"
+fi
+
+AC_SUBST(APXS2_CFLAGS)
+AC_SUBST(APXS2_INCLUDE)
+
+
+# Apache 2.2 (mod_shib_22)
+#   --enable-apache-22
+#   --with-apxs22     (DSO build, the normal way, uses apxs to derive build flags)
+#   --with-apr1       (DSO build, APR development package installed separately)
+#   --with-apu1       (DSO build, APR-UTIL development package installed separately)
+
+AC_ARG_ENABLE(apache-22,
+	AS_HELP_STRING([--enable-apache-22],[enable the Apache 2.2 module]),
+	[if test "x$enableval" = "x" ; then
+         WANT_APACHE_22=yes
+	 else
+	     WANT_APACHE_22="$enableval"
+	 fi
+	],[ WANT_APACHE_22=no ])
+AC_MSG_CHECKING(whether to build Apache 2.2 module)
+if test "$WANT_APACHE_22" != yes && test "$WANT_APACHE_22" != no ; then
+    WANT_APACHE_22=yes
+fi
+AC_MSG_RESULT($WANT_APACHE_22)
+
+if test "$WANT_APACHE_22" = "yes" ; then
+    AC_ARG_WITH(apxs22, 
+        AS_HELP_STRING([--with-apxs22=FILE],[Specifies where to find the Apache 2.2 apxs script.]),
+        [
+        AC_MSG_CHECKING(for user-specified Apache 2.2 apxs name/location)
+        if test "$withval" != "no" ; then
+          if test "$withval" != "yes"; then
+            APXS22=$withval
+            AC_MSG_RESULT("$withval")
+          fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APXS22, apxs2, no)
+        if test "$APXS22" = "no" ; then
+            AC_PATH_PROG(APXS22, apxs, no)
+        fi
+        if test "$APXS22" = "no" ; then
+          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+            if test "$APXS22" = "no" && test -f "$i/apxs2" ; then
+              APXS22="$i/apxs2"
+            fi
+          done
+          if test "$APXS22" = "no" ; then
+            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+              if test "$APXS22" = "no" && test -f "$i/apxs" ; then
+                APXS22="$i/apxs"
+              fi
+            done
+          fi
+        fi
+        ])
+
+    AC_MSG_CHECKING([to see if Apache 2.2 apxs was located])
+    if test ! -f "$APXS22" ; then
+        AC_MSG_RESULT(no)
+        AC_MSG_ERROR([Unable to locate Apache 2.2 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs22 option.])
+    fi
+    AC_MSG_RESULT($APXS22)
+    AC_SUBST(APXS22)
+
+    # APR1 settings
+    AC_ARG_WITH(apr1, 
+        AS_HELP_STRING([--with-apr1=PATH],[where apr-1-config is installed]),
+        [
+        AC_MSG_CHECKING(for user-specified apr-1-config name/location)
+        if test "$withval" != "no" ; then
+            if test "$withval" != "yes"; then
+                APR1_CONFIG=$withval
+                AC_MSG_RESULT("$withval")
+            fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APR1_CONFIG, apr-1-config,,[`$APXS22 -q SBINDIR`]:[$PATH])
+        ])
+	if test -f "${APR1_CONFIG}"; then
+        APR1_CFLAGS="`${APR1_CONFIG} --cflags` `${APR1_CONFIG} --cppflags` `${APR1_CONFIG} --includes`"
+    else
+        AC_MSG_ERROR([Unable to locate apr-1-config, may need --with-apr1 option.])
+    fi
+
+    # APU1 settings
+    AC_ARG_WITH(apu1, 
+        AS_HELP_STRING([--with-apu1=PATH],[where apu-1-config is installed]),
+        [
+        AC_MSG_CHECKING(for user-specified apu-1-config name/location)
+        if test "$withval" != "no" ; then
+            if test "$withval" != "yes"; then
+                APU1_CONFIG=$withval
+                AC_MSG_RESULT("$withval")
+            fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APU1_CONFIG, apu-1-config,,[`$APXS22 -q SBINDIR`]:[$PATH])
+        ])
+    if test -f "${APU1_CONFIG}"; then
+        APU1_CFLAGS="`${APU1_CONFIG} --includes`"
+    else
+        AC_MSG_ERROR([Unable to locate apu-1-config, may need --with-apu1 option.])
+    fi
+
+    # extract settings we need from APXS22 -q
+    APXS22_CC="`$APXS22 -q CC`"
+    APXS22_CFLAGS="`$APXS22 -q CPPFLAGS` `$APXS22 -q CFLAGS` $APR1_CFLAGS $APU1_CFLAGS"
+    APXS22_INCLUDE="`$APXS22 -q INCLUDEDIR`"
+fi
+
+AC_SUBST(APXS22_CFLAGS)
+AC_SUBST(APXS22_INCLUDE)
+
+# Apache 2.4 (mod_shib_24)
+#   --enable-apache-24
+#   --with-apxs24     (DSO build, the normal way, uses apxs to derive build flags)
+#   --with-apr1       (DSO build, APR development package installed separately)
+#   --with-apu1       (DSO build, APR-UTIL development package installed separately)
+
+AC_ARG_ENABLE(apache-24,
+	AS_HELP_STRING([--enable-apache-24],[enable the Apache 2.4 module]),
+	[if test "x$enableval" = "x" ; then
+         WANT_APACHE_24=yes
+	 else
+	     WANT_APACHE_24="$enableval"
+	 fi
+	],[ WANT_APACHE_24=no ])
+AC_MSG_CHECKING(whether to build Apache 2.4 module)
+if test "$WANT_APACHE_24" != yes && test "$WANT_APACHE_24" != no ; then
+    WANT_APACHE_24=yes
+fi
+AC_MSG_RESULT($WANT_APACHE_24)
+
+if test "$WANT_APACHE_24" = "yes" ; then
+    AC_ARG_WITH(apxs24, 
+        AS_HELP_STRING([--with-apxs24=FILE],[Specifies where to find the Apache 2.4 apxs script.]),
+        [
+        AC_MSG_CHECKING(for user-specified Apache 2.4 apxs name/location)
+        if test "$withval" != "no" ; then
+          if test "$withval" != "yes"; then
+            APXS24=$withval
+            AC_MSG_RESULT("$withval")
+          fi
+        fi
+        ],
+        [
+        AC_PATH_PROG(APXS24, apxs2, no)
+        if test "$APXS24" = "no" ; then
+            AC_PATH_PROG(APXS24, apxs, no)
+        fi
+        if test "$APXS24" = "no" ; then
+          for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+            if test "$APXS24" = "no" && test -f "$i/apxs2" ; then
+              APXS24="$i/apxs2"
+            fi
+          done
+          if test "$APXS24" = "no" ; then
+            for i in /usr/sbin /usr/local/apache2/bin /usr/local/apache/bin ; do
+              if test "$APXS24" = "no" && test -f "$i/apxs" ; then
+                APXS24="$i/apxs"
+              fi
+            done
+          fi
+        fi
+        ])
+
+    AC_MSG_CHECKING([to see if Apache 2.4 apxs was located])
+    if test ! -f "$APXS24" ; then
+        AC_MSG_RESULT(no)
+        AC_MSG_ERROR([Unable to locate Apache 2.4 apxs script. An Apache development package may be missing from your server, or you may need to use the --with-apxs24 option.])
+    fi
+    AC_MSG_RESULT($APXS24)
+    AC_SUBST(APXS24)
+
+    # If we haven't done this work already for Apache 2.2
+    if test "$WANT_APACHE_22" != "yes" ; then
+        # APR1 settings
+        AC_ARG_WITH(apr1,
+            AS_HELP_STRING([--with-apr1=PATH],[where apr-1-config is installed]),
+            [
+            AC_MSG_CHECKING(for user-specified apr-1-config name/location)
+            if test "$withval" != "no" ; then
+                if test "$withval" != "yes"; then
+                    APR1_CONFIG=$withval
+                    AC_MSG_RESULT("$withval")
+                fi
+            fi
+            ],
+            [
+            AC_PATH_PROG(APR1_CONFIG, apr-1-config,,[`$APXS24 -q SBINDIR`]:[$PATH])
+            ])
+        if test -f "${APR1_CONFIG}"; then
+            APR1_CFLAGS="`${APR1_CONFIG} --cflags` `${APR1_CONFIG} --cppflags` `${APR1_CONFIG} --includes`"
+        else
+            AC_MSG_ERROR([Unable to locate apr-1-config, may need --with-apr1 option.])
+        fi
+
+        # APU1 settings
+        AC_ARG_WITH(apu1,
+            AS_HELP_STRING([--with-apu1=PATH],[where apu-1-config is installed]),
+            [
+            AC_MSG_CHECKING(for user-specified apu-1-config name/location)
+            if test "$withval" != "no" ; then
+                if test "$withval" != "yes"; then
+                    APU1_CONFIG=$withval
+                    AC_MSG_RESULT("$withval")
+                fi
+            fi
+            ],
+            [
+            AC_PATH_PROG(APU1_CONFIG, apu-1-config,,[`$APXS24 -q SBINDIR`]:[$PATH])
+            ])
+        if test -f "${APU1_CONFIG}"; then
+            APU1_CFLAGS="`${APU1_CONFIG} --includes`"
+        else
+            AC_MSG_ERROR([Unable to locate apu-1-config, may need --with-apu1 option.])
+        fi
+    fi
+    
+    # extract settings we need from APXS24 -q
+    APXS24_CC="`$APXS24 -q CC`"
+    APXS24_CFLAGS="`$APXS24 -q CPPFLAGS` `$APXS24 -q CFLAGS` $APR1_CFLAGS $APU1_CFLAGS"
+    APXS24_INCLUDE="`$APXS24 -q INCLUDEDIR`"
+fi
+
+AC_SUBST(APXS24_CFLAGS)
+AC_SUBST(APXS24_INCLUDE)
+
+# always output the Makefile, even if you don't use it
+AC_CONFIG_FILES([apache/Makefile])
+AM_CONDITIONAL(BUILD_AP13,test "$WANT_APACHE_13" = "yes")
+AM_CONDITIONAL(BUILD_AP20,test "$WANT_APACHE_20" = "yes")
+AM_CONDITIONAL(BUILD_AP22,test "$WANT_APACHE_22" = "yes")
+AM_CONDITIONAL(BUILD_AP24,test "$WANT_APACHE_24" = "yes")
+
+# add the apache module to the list of wanted subdirs..
+if test "$WANT_APACHE_13" = "yes" || test "$WANT_APACHE_20" = "yes" || test "$WANT_APACHE_22" = "yes" || test "$WANT_APACHE_24" = "yes" ; then
+    WANT_SUBDIRS="$WANT_SUBDIRS apache"
+fi
+
+
+#
+# Implement the checks of the ODBC Storage Service
+#
+# 1) Assume the user wants ODBC; if it's not found then just continue without
+# 2) If the user specifically requested odbc, look for it and ERROR if not found
+# 3) If the user specifically requested no odbc, don't build it.
+#
+
+AC_CONFIG_FILES([odbc-store/Makefile])
+
+# determine whether we should enable the odbc ccache
+AC_ARG_ENABLE([odbc],
+	AS_HELP_STRING([--disable-odbc],[disable the ODBC Storage Service]),
+	[odbc_enabled=$enableval], [odbc_enabled=default])
+if test "x$odbc_enabled" = "x" ; then
+    odbc_enabled=yes
+fi
+
+# Are we trying to build ODBC?
+AC_MSG_CHECKING(whether to build the ODBC storage service)
+if test "$odbc_enabled" = "yes" ; then
+    build_odbc=yes
+    AC_MSG_RESULT(yes)
+elif test "$odbc_enabled" = "default" ; then
+    build_odbc=yes
+    AC_MSG_RESULT([yes, if it can be found])
+else
+    build_odbc=no
+    AC_MSG_RESULT(no)
+fi
+
+# If we're trying to build ODBC, try to find the odbc_config program.
+if test "$build_odbc" = "yes" ; then
+    odbc_dir=""
+    AC_ARG_WITH(odbc,
+	   AS_HELP_STRING([--with-odbc=PATH],[directory where odbc is installed]),
+	    [if test "$with_odbc" = no ; then
+            AC_MSG_ERROR([Try running --disable-odbc instead.])
+         elif test "$with_odbc" != yes ; then
+            odbc_dir="$with_odbc/bin"
+            if test "$with_odbc" != /usr ; then
+                ODBC_CFLAGS="-I$with_odbc/include"
+                ODBC_LIBS="-L$with_odbc/lib"
+            fi
+         fi])
+
+   AC_PATH_PROG(ODBC_CONFIG, odbc_config, no, $odbc_dir $PATH )
+   if test "$ODBC_CONFIG" = no ; then
+      AC_MSG_WARN([Cannot find odbc_config, will try to guess settings.])
+      ODBC_LIBS="$ODBC_LIBS -lodbc"
+   else
+      ODBC_CFLAGS=`$ODBC_CONFIG --cflags`
+      ODBC_LIBS=`$ODBC_CONFIG --libs`
+   fi
+
+   save_CPPFLAGS="$CPPFLAGS"
+   CPPFLAGS="$CPPFLAGS $ODBC_CFLAGS"
+
+   AC_CHECK_HEADER([sql.h], [have_sql_h=yes], [have_sql_h=no])
+   if test "$have_sql_h" = no -a "$odbc_enabled" = "yes" ; then
+     AC_MSG_ERROR(unable to find ODBC header files)
+   fi
+
+   if test "$have_sql_h" = yes ; then
+      save_LIBS="$LIBS"
+      LIBS="$LIBS $ODBC_LIBS"
+      AC_MSG_CHECKING(if we can link againt ODBC)
+      AC_LINK_IFELSE(
+        [AC_LANG_PROGRAM([[#include <sql.h>
+ #include <sqlext.h>
+ #include <stdio.h>]],
+            [[SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, (void*)SQL_CP_ONE_PER_HENV, 0)]])],
+        [have_odbc_libs=yes],[have_odbc_libs=no])
+      LIBS="$save_LIBS"
+      if test "$have_odbc_libs" = no ; then
+         if test "$odbc_enabled" = "yes" ; then
+            AC_MSG_ERROR([unable to link with ODBC Library])
+         else
+            AC_MSG_RESULT([no, skipping ODBC])
+         fi
+      fi
+   fi
+
+   CPPFLAGS="$save_CPPFLAGS"
+fi
+
+# if have_odbc_libs=yes then go ahead with building ODBC
+if test "$have_odbc_libs" = yes ; then
+   # this AC_MSG_RESULT is from above!
+   AC_MSG_RESULT(yes)
+   WANT_SUBDIRS="$WANT_SUBDIRS odbc-store"
+   AC_SUBST(ODBC_CFLAGS)
+   AC_SUBST(ODBC_LIBS)
+fi
+
+# GSS-API checking
+
+GSSAPI_ROOT="/usr"
+AC_ARG_WITH(gssapi-includes,
+  AS_HELP_STRING([--with-gssapi-includes=DIR],[Specify location of GSSAPI header]),
+  [ GSSAPI_INCS="-I$withval"
+    want_gss="yes" ]
+)
+
+AC_ARG_WITH(gssapi-libs,
+  AS_HELP_STRING([--with-gssapi-libs=DIR],[Specify location of GSSAPI libs]),
+  [ GSSAPI_LIB_DIR="-L$withval"
+    want_gss="yes" ]
+)
+
+AC_ARG_WITH(gssapi,
+  AS_HELP_STRING([--with-gssapi=DIR],[Where to look for GSSAPI]),
+  [ GSSAPI_ROOT="$withval"
+  if test x"$GSSAPI_ROOT" != xno; then
+    want_gss="yes"
+    if test x"$GSSAPI_ROOT" = xyes; then
+      dnl if yes, then use default root
+      GSSAPI_ROOT="/usr"
+    fi
+  fi
+])
+
+save_CPPFLAGS="$CPPFLAGS"
+AC_MSG_CHECKING([if GSSAPI support is requested])
+if test x"$want_gss" = xyes; then
+  AC_MSG_RESULT(yes)
+
+  if test -z "$GSSAPI_INCS"; then
+     if test -f "$GSSAPI_ROOT/bin/krb5-config"; then
+        GSSAPI_INCS=`$GSSAPI_ROOT/bin/krb5-config --cflags gssapi`
+     elif test "$GSSAPI_ROOT" != "yes"; then
+        GSSAPI_INCS="-I$GSSAPI_ROOT/include"
+     fi
+  fi
+
+  CPPFLAGS="$CPPFLAGS $GSSAPI_INCS"
+
+  AC_CHECK_HEADER(gss.h,
+    [
+      dnl found in the given dirs
+      AC_DEFINE([SHIBSP_HAVE_GSSGNU],[1],[if you have the GNU gssapi libraries])
+      gnu_gss=yes
+    ],
+    [
+      dnl not found, check Heimdal or MIT
+      AC_CHECK_HEADERS([gssapi/gssapi.h], [], [not_mit=1])
+      AC_CHECK_HEADERS(
+        [gssapi/gssapi_generic.h gssapi/gssapi_krb5.h],
+        [],
+        [not_mit=1],
+        [
+AC_INCLUDES_DEFAULT
+#ifdef HAVE_GSSAPI_GSSAPI_H
+#include <gssapi/gssapi.h>
+#endif
+        ])
+      if test "x$not_mit" = "x1"; then
+        dnl MIT not found, check for Heimdal
+        AC_CHECK_HEADER([gssapi.h],
+            [
+              dnl found
+              AC_DEFINE([SHIBSP_HAVE_GSSHEIMDAL],[1],[if you have the Heimdal gssapi libraries])
+            ],
+            [
+              dnl no header found, disabling GSS
+              want_gss=no
+              AC_MSG_WARN([disabling GSSAPI since no header files was found])
+            ]
+          )
+      else
+        dnl MIT found
+        AC_DEFINE([SHIBSP_HAVE_GSSMIT],[1],[if you have the MIT gssapi libraries])
+        dnl check if we have a really old MIT kerberos (<= 1.2)
+        AC_MSG_CHECKING([if gssapi headers declare GSS_C_NT_HOSTBASED_SERVICE])
+        AC_COMPILE_IFELSE([
+          AC_LANG_PROGRAM([[
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_generic.h>
+#include <gssapi/gssapi_krb5.h>
+          ]],[[
+            gss_import_name(
+                            (OM_uint32 *)0,
+                            (gss_buffer_t)0,
+                            GSS_C_NT_HOSTBASED_SERVICE,
+                            (gss_name_t *)0);
+          ]])
+        ],[
+          AC_MSG_RESULT([yes])
+        ],[
+          AC_MSG_RESULT([no])
+          AC_DEFINE([HAVE_OLD_GSSMIT],[1],[if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE])
+        ])
+      fi
+    ]
+  )
+else
+  AC_MSG_RESULT(no)
+fi
+if test x"$want_gss" = xyes; then
+  AC_DEFINE([SHIBSP_HAVE_GSSAPI],[1],[if you have the gssapi libraries])
+
+  if test -n "$gnu_gss"; then
+    LDFLAGS="$LDFLAGS $GSSAPI_LIB_DIR"
+    LIBS="$LIBS -lgss"
+  else
+    if test -z "$GSSAPI_LIB_DIR"; then
+      GSSAPI_LIB_DIR="$GSSAPI_ROOT/lib$libsuff"
+    fi
+    if test "$GSSAPI_ROOT" != "yes"; then
+       LDFLAGS="$LDFLAGS -L$GSSAPI_ROOT/lib$libsuff"
+    fi
+    if test -f "$GSSAPI_ROOT/bin/krb5-config"; then
+      dnl krb5-config doesn't have --libs-only-L or similar, put everything
+      dnl into LIBS
+      gss_libs=`$GSSAPI_ROOT/bin/krb5-config --libs gssapi`
+    else
+      if test "x$not_mit" = "x1"; then
+        gss_libs="-lgssapi"
+      else
+        gss_libs="-lgssapi_krb5"
+      fi
+    fi
+    LIBS="$LIBS $gss_libs"
+  fi
+
+  AC_MSG_CHECKING([whether GSS-API naming extensions are available])
+  AC_COMPILE_IFELSE(
+    [AC_LANG_PROGRAM([[
+#ifdef SHIBSP_HAVE_GSSGNU
+# include <gss.h>
+#elif defined SHIBSP_HAVE_GSSMIT
+# include <gssapi/gssapi.h>
+# include <gssapi/gssapi_ext.h>
+#else
+# include <gssapi.h>
+#endif]],
+    [[gss_get_name_attribute(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);]])],
+    [AC_MSG_RESULT([yes])AC_DEFINE([HAVE_GSSAPI_NAMINGEXTS],[1],[Define to 1 if GSS-API naming extensions are available.])],
+    [AC_MSG_RESULT([no])])
+
+  AC_MSG_CHECKING([whether GSS-API composite name import is available])
+  AC_COMPILE_IFELSE(
+    [AC_LANG_PROGRAM([[
+#ifdef SHIBSP_HAVE_GSSGNU
+# include <gss.h>
+#elif defined SHIBSP_HAVE_GSSMIT
+# include <gssapi/gssapi.h>
+# include <gssapi/gssapi_ext.h>
+#else
+# include <gssapi.h>
+#endif]],
+    [[
+    OM_uint32 minor;
+    gss_name_t srcname;
+    gss_buffer_desc importbuf;
+    gss_import_name(&minor, &importbuf, GSS_C_NT_EXPORT_NAME_COMPOSITE, &srcname);
+    ]])],
+    [AC_MSG_RESULT([yes])AC_DEFINE([HAVE_GSSAPI_COMPOSITE_NAME],[1],[Define to 1 if GSS-API composite name import is available.])],
+    [AC_MSG_RESULT([no])])
+    
+else
+  CPPFLAGS="$save_CPPFLAGS"
+fi
+
+
+AC_SUBST(WANT_SUBDIRS)
+
+if test -n "$APXS_CC" && test "$APXS_CC" != "$CC" ; then
+  echo "=================================================================="
+  echo "WARNING: You have chosen to compile Apache-1.3 modules with a different"
+  echo "         compiler than the one used to compile Apache."
+  echo ""
+  echo "    Current compiler:      $CC"
+  echo "   Apache's compiler:      $APXS_CC"
+  echo ""
+  echo "This could cause problems."
+  echo "=================================================================="
+fi
+
+if test -n "$APXS2_CC" && test "$APXS2_CC" != "$CC" ; then
+  echo "=================================================================="
+  echo "WARNING: You have chosen to compile Apache-2.0 modules with a different"
+  echo "         compiler than the one used to compile Apache."
+  echo ""
+  echo "    Current compiler:      $CC"
+  echo "   Apache's compiler:      $APXS2_CC"
+  echo ""
+  echo "This could cause problems."
+  echo "=================================================================="
+fi
+
+if test -n "$APXS22_CC" && test "$APXS22_CC" != "$CC" ; then
+  echo "=================================================================="
+  echo "WARNING: You have chosen to compile Apache-2.2 modules with a different"
+  echo "         compiler than the one used to compile Apache."
+  echo ""
+  echo "    Current compiler:      $CC"
+  echo "   Apache's compiler:      $APXS22_CC"
+  echo ""
+  echo "This could cause problems."
+  echo "=================================================================="
+fi
+
+if test -n "$APXS24_CC" && test "$APXS24_CC" != "$CC" ; then
+  echo "=================================================================="
+  echo "WARNING: You have chosen to compile Apache-2.4 modules with a different"
+  echo "         compiler than the one used to compile Apache."
+  echo ""
+  echo "    Current compiler:      $CC"
+  echo "   Apache's compiler:      $APXS24_CC"
+  echo ""
+  echo "This could cause problems."
+  echo "=================================================================="
+fi
+
+LIBTOOL="$LIBTOOL --silent"
+
+AC_OUTPUT
diff --git a/doc/README.txt b/doc/README.txt
index 59e03e4..7a961be 100644
--- a/doc/README.txt
+++ b/doc/README.txt
@@ -1,22 +1,22 @@
-Shibboleth is a federated web authentication and attribute exchange system
-based on SAML, originally developed by Internet2 and now a product of the
-Shibboleth Consortium.
-
-Please review the terms described in the LICENSE.txt file before using this
-code. It is the standard Apache 2.0 license.
-
-A wealth of information about Shibboleth can be found at
-http://shibboleth.net/
-
-Shibboleth is divided into identity and service provider components, with the
-IdP in Java and the SP (this software) in C++.
-
-Source and binary distributions are available from
-http://shibboleth.net/downloads/
-
-The source is available in Git, as described in the Shibboleth
-site. Mailing lists and a bug database (https://issues.shibboleth.net/) are
-also available.
-
-For basic information on building from source, using binaries, and deploying
-Shibboleth, refer to the web site and Wiki for the latest documentation.
+Shibboleth is a federated web authentication and attribute exchange system
+based on SAML, originally developed by Internet2 and now a product of the
+Shibboleth Consortium.
+
+Please review the terms described in the LICENSE.txt file before using this
+code. It is the standard Apache 2.0 license.
+
+A wealth of information about Shibboleth can be found at
+http://shibboleth.net/
+
+Shibboleth is divided into identity and service provider components, with the
+IdP in Java and the SP (this software) in C++.
+
+Source and binary distributions are available from
+http://shibboleth.net/downloads/
+
+The source is available in Git, as described in the Shibboleth
+site. Mailing lists and a bug database (https://issues.shibboleth.net/) are
+also available.
+
+For basic information on building from source, using binaries, and deploying
+Shibboleth, refer to the web site and Wiki for the latest documentation.
diff --git a/shibsp/version.h b/shibsp/version.h
index 949e5cc..4440a51 100644
--- a/shibsp/version.h
+++ b/shibsp/version.h
@@ -1,80 +1,80 @@
-/**
- * Licensed to the University Corporation for Advanced Internet
- * Development, Inc. (UCAID) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for
- * additional information regarding copyright ownership.
- *
- * UCAID licenses this file to you 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
- *
- * 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.
- */
-
-/**
- * version.h
- *
- * Library version macros and constants.
- */
-
-#ifndef __shibsp_version_h__
-#define __shibsp_version_h__
-
-// This is all based on Xerces, on the theory it might be useful to
-// support this kind of stuff in the future. If they ever yank some
-// of this stuff, it can be copied into here.
-
-#include <shibsp/base.h>
-#include <xercesc/util/XercesVersion.hpp>
-
-// ---------------------------------------------------------------------------
-// V E R S I O N   S P E C I F I C A T I O N
-
-/**
- * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH SHIBSP LIBRARY VERSION
- * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
- */
-
-#define SHIBSP_VERSION_MAJOR 1
-#define SHIBSP_VERSION_MINOR 5
-#define SHIBSP_VERSION_REVISION 6
-
-/** DO NOT MODIFY BELOW THIS LINE */
-
-/**
- * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
- *
- *	gShibSPVersionStr, gShibSPFullVersionStr, gShibSPMajVersion, gShibSPMinVersion, gShibSPRevision
- */
-
-// ---------------------------------------------------------------------------
-// V E R S I O N   I N F O R M A T I O N
-
-// ShibSP version strings; these particular macros cannot be used for
-// conditional compilation as they are not numeric constants
-
-#define SHIBSP_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
-#define SHIBSP_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
-#define SHIBSP_FULLVERSIONNUM INVK_CAT3_SEP_NIL(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
-#define SHIBSP_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR)
-
-extern SHIBSP_API const char* const    gShibSPVersionStr;
-extern SHIBSP_API const char* const    gShibSPFullVersionStr;
-extern SHIBSP_API const char* const    gShibSPDotVersionStr;
-extern SHIBSP_API const unsigned int   gShibSPMajVersion;
-extern SHIBSP_API const unsigned int   gShibSPMinVersion;
-extern SHIBSP_API const unsigned int   gShibSPRevision;
-
-// ShibSP version numeric constants that can be used for conditional
-// compilation purposes.
-
-#define _SHIBSP_VERSION CALC_EXPANDED_FORM (SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
-
-#endif /* __shibsp_version_h__ */
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
+ *
+ * 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.
+ */
+
+/**
+ * version.h
+ *
+ * Library version macros and constants.
+ */
+
+#ifndef __shibsp_version_h__
+#define __shibsp_version_h__
+
+// This is all based on Xerces, on the theory it might be useful to
+// support this kind of stuff in the future. If they ever yank some
+// of this stuff, it can be copied into here.
+
+#include <shibsp/base.h>
+#include <xercesc/util/XercesVersion.hpp>
+
+// ---------------------------------------------------------------------------
+// V E R S I O N   S P E C I F I C A T I O N
+
+/**
+ * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH SHIBSP LIBRARY VERSION
+ * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
+ */
+
+#define SHIBSP_VERSION_MAJOR 1
+#define SHIBSP_VERSION_MINOR 5
+#define SHIBSP_VERSION_REVISION 6
+
+/** DO NOT MODIFY BELOW THIS LINE */
+
+/**
+ * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
+ *
+ *	gShibSPVersionStr, gShibSPFullVersionStr, gShibSPMajVersion, gShibSPMinVersion, gShibSPRevision
+ */
+
+// ---------------------------------------------------------------------------
+// V E R S I O N   I N F O R M A T I O N
+
+// ShibSP version strings; these particular macros cannot be used for
+// conditional compilation as they are not numeric constants
+
+#define SHIBSP_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
+#define SHIBSP_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
+#define SHIBSP_FULLVERSIONNUM INVK_CAT3_SEP_NIL(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
+#define SHIBSP_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR)
+
+extern SHIBSP_API const char* const    gShibSPVersionStr;
+extern SHIBSP_API const char* const    gShibSPFullVersionStr;
+extern SHIBSP_API const char* const    gShibSPDotVersionStr;
+extern SHIBSP_API const unsigned int   gShibSPMajVersion;
+extern SHIBSP_API const unsigned int   gShibSPMinVersion;
+extern SHIBSP_API const unsigned int   gShibSPRevision;
+
+// ShibSP version numeric constants that can be used for conditional
+// compilation purposes.
+
+#define _SHIBSP_VERSION CALC_EXPANDED_FORM (SHIBSP_VERSION_MAJOR,SHIBSP_VERSION_MINOR,SHIBSP_VERSION_REVISION)
+
+#endif /* __shibsp_version_h__ */

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-shibboleth/shibboleth-sp2.git



More information about the Pkg-shibboleth-devel mailing list