Port up context changes to prevent false spoofing error.
[shibboleth/sp.git] / isapi_shib / isapi_shib.cpp
index 726798a..1f01f44 100644 (file)
 /*
- * The Shibboleth License, Version 1.
- * Copyright (c) 2002
- * University Corporation for Advanced Internet Development, Inc.
- * All rights reserved
+ *  Copyright 2001-2007 Internet2
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution, if any, must include
- * the following acknowledgment: "This product includes software developed by
- * the University Corporation for Advanced Internet Development
- * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
- * may appear in the software itself, if and wherever such third-party
- * acknowledgments normally appear.
- *
- * Neither the name of Shibboleth nor the names of its contributors, nor
- * Internet2, nor the University Corporation for Advanced Internet Development,
- * Inc., nor UCAID may be used to endorse or promote products derived from this
- * software without specific prior written permission. For written permission,
- * please contact shibboleth@shibboleth.org
- *
- * Products derived from this software may not be called Shibboleth, Internet2,
- * UCAID, or the University Corporation for Advanced Internet Development, nor
- * may Shibboleth appear in their name, without prior written permission of the
- * University Corporation for Advanced Internet Development.
- *
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
- * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
- * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
- * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
-/* isapi_shib.cpp - Shibboleth ISAPI filter
-
-   Scott Cantor
-   8/23/02
-*/
+/**
+ * isapi_shib.cpp
+ * 
+ * Shibboleth ISAPI filter
+ */
 
-#include <windows.h>
-#include <httpfilt.h>
+#define SHIBSP_LITE
+#include "config_win32.h"
 
-// SAML Runtime
-#include <saml.h>
-#include <shib.h>
-#include <eduPerson.h>
+#define _CRT_NONSTDC_NO_DEPRECATE 1
+#define _CRT_SECURE_NO_DEPRECATE 1
 
-#include <log4cpp/Category.hh>
-#include <log4cpp/PropertyConfigurator.hh>
+#include <shibsp/AbstractSPRequest.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.h>
+#include <xmltooling/unicode.h>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
 #include <xercesc/util/Base64.hpp>
+#include <xercesc/util/XMLUniDefs.hpp>
 
-#include <ctime>
-#include <strstream>
-#include <stdexcept>
-
-using namespace std;
-using namespace log4cpp;
-using namespace saml;
-using namespace shibboleth;
-using namespace eduPerson;
-
-class CCacheEntry;
-class CCache
-{
-public:
-    CCache();
-    ~CCache();
-
-    SAMLBinding* getBinding(const XMLCh* bindingProt);
-    CCacheEntry* find(const char* key);
-    void insert(const char* key, CCacheEntry* entry);
-    void remove(const char* key);
-    void sweep(time_t lifetime);
-
-    bool lock() { EnterCriticalSection(&m_lock); return true; }
-    void unlock() { LeaveCriticalSection(&m_lock); }
-
-private:
-    SAMLBinding* m_SAMLBinding;
-    map<string,CCacheEntry*> m_hashtable;
-    CRITICAL_SECTION m_lock;
-};
-
-// Per-website global structure
-struct settings_t
-{
-    settings_t();
-    string g_CookieName;                    // name of authentication token
-    string g_WAYFLocation;                  // URL of WAYF service
-    string g_GarbageCollector;              // URL of cache garbage collection service
-    string g_SHIRELocation;                 // URL of SHIRE acceptance point
-    string g_SHIRESessionPath;              // path to storage for sessions
-    vector<string> g_MustContain;           // simple URL matching string array
-    bool g_bSSLOnly;                        // only over SSL?
-    time_t g_Lifetime;                      // maximum token lifetime
-    time_t g_Timeout;                       // maximum time between uses
-    bool g_bCheckAddress;                   // validate IP addresses?
-    bool g_bExportAssertion;                // export SAML assertion to header?
-    CCache g_AuthCache;                     // local auth cache
-};
-
-settings_t::settings_t()
-{
-    g_bSSLOnly=true;
-    g_Lifetime=7200;
-    g_Timeout=3600;
-    g_bCheckAddress=true;
-    g_bExportAssertion=false;
-}
-
-class CCacheEntry
-{
-public:
-    CCacheEntry(const char* sessionFile);
-    ~CCacheEntry();
-
-    SAMLAuthorityBinding* getBinding() { return m_binding; }
-    Iterator<SAMLAttribute*> getAttributes(const char* resource_url, settings_t* pSite);
-    const XMLByte* getSerializedAssertion(const char* resource_url, settings_t* pSite);
-    bool isSessionValid(time_t lifetime, time_t timeout);
-    const XMLCh* getHandle() { return m_handle.c_str(); }
-    const XMLCh* getOriginSite() { return m_originSite.c_str(); }
-    const char* getClientAddress() { return m_clientAddress.c_str(); }
-
-private:
-    void populate(const char* resource_url, settings_t* pSite);
-
-    xstring m_originSite;
-    xstring m_handle;
-    SAMLAuthorityBinding* m_binding;
-    string m_clientAddress;
-    SAMLResponse* m_response;
-    SAMLAssertion* m_assertion;
-    time_t m_sessionCreated;
-    time_t m_lastAccess;
-    XMLByte* m_serialized;
-
-    static saml::QName g_authorityKind;
-    static saml::QName g_respondWith;
-    friend class CCache;
-};
-
-// static members
-saml::QName CCacheEntry::g_authorityKind(saml::XML::SAMLP_NS,L(AttributeQuery));
-saml::QName CCacheEntry::g_respondWith(saml::XML::SAML_NS,L(AttributeStatement));
-
-CCache::CCache()
-{
-    m_SAMLBinding=SAMLBindingFactory::getInstance();
-    InitializeCriticalSection(&m_lock);
-}
-
-CCache::~CCache()
-{
-    DeleteCriticalSection(&m_lock);
-    delete m_SAMLBinding;
-    for (map<string,CCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end(); i++)
-        delete i->second;
-}
-
-SAMLBinding* CCache::getBinding(const XMLCh* bindingProt)
-{
-    if (!XMLString::compareString(bindingProt,SAMLBinding::SAML_SOAP_HTTPS))
-        return m_SAMLBinding;
-    return NULL;
-}
-
-CCacheEntry* CCache::find(const char* key)
-{
-    map<string,CCacheEntry*>::const_iterator i=m_hashtable.find(key);
-    if (i==m_hashtable.end())
-        return NULL;
-    return i->second;
-}
-
-void CCache::insert(const char* key, CCacheEntry* entry)
-{
-    m_hashtable[key]=entry;
-}
-
-void CCache::remove(const char* key)
-{
-    m_hashtable.erase(key);
-}
+#include <set>
+#include <sstream>
+#include <fstream>
+#include <process.h>
 
-void CCache::sweep(time_t lifetime)
-{
-    time_t now=time(NULL);
-    for (map<string,CCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end();)
-    {
-        if (lifetime > 0 && now > i->second->m_sessionCreated+lifetime)
-        {
-            delete i->second;
-            i=m_hashtable.erase(i);
-        }
-        else
-            i++;
-    }
-}
-
-CCacheEntry::CCacheEntry(const char* sessionFile)
-  : m_binding(NULL), m_assertion(NULL), m_response(NULL), m_lastAccess(0), m_sessionCreated(0), m_serialized(NULL)
-{
-    FILE* f;
-    char line[1024];
-    const char* token = NULL;
-    char* w = NULL;
-    auto_ptr<XMLCh> binding,location;
+#include <windows.h>
+#include <httpfilt.h>
+#include <httpext.h>
 
-    if (!(f=fopen(sessionFile,"r")))
-    {
-        fprintf(stderr,"CCacheEntry() could not open session file: %s",sessionFile);
-        throw runtime_error("CCacheEntry() could not open session file");
-    }
+using namespace shibsp;
+using namespace xmltooling;
+using namespace xercesc;
+using namespace std;
 
-    while (fgets(line,1024,f))
-    {
-        if ((*line=='#') || (!*line))
-            continue;
-        token = line;
-        w=strchr(token,'=');
-        if (!w)
-            continue;
-        *w++=0;
-        if (w[strlen(w)-1]=='\n')
-            w[strlen(w)-1]=0;
-
-        if (!strcmp("Domain",token))
-        {
-               auto_ptr<XMLCh> origin(XMLString::transcode(w));
-               m_originSite=origin.get();
-        }
-        else if (!strcmp("Handle",token))
+// globals
+namespace {
+    static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);
+    static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
+    static const XMLCh name[] =             UNICODE_LITERAL_4(n,a,m,e);
+    static const XMLCh port[] =             UNICODE_LITERAL_4(p,o,r,t);
+    static const XMLCh sslport[] =          UNICODE_LITERAL_7(s,s,l,p,o,r,t);
+    static const XMLCh scheme[] =           UNICODE_LITERAL_6(s,c,h,e,m,e);
+    static const XMLCh id[] =               UNICODE_LITERAL_2(i,d);
+    static const XMLCh ISAPI[] =            UNICODE_LITERAL_5(I,S,A,P,I);
+    static const XMLCh Alias[] =            UNICODE_LITERAL_5(A,l,i,a,s);
+    static const XMLCh normalizeRequest[] = UNICODE_LITERAL_16(n,o,r,m,a,l,i,z,e,R,e,q,u,e,s,t);
+    static const XMLCh Site[] =             UNICODE_LITERAL_4(S,i,t,e);
+
+    struct site_t {
+        site_t(const DOMElement* e)
         {
-               auto_ptr<XMLCh> handle(XMLString::transcode(w));
-               m_handle=handle.get();
+            auto_ptr_char n(e->getAttributeNS(NULL,name));
+            auto_ptr_char s(e->getAttributeNS(NULL,scheme));
+            auto_ptr_char p(e->getAttributeNS(NULL,port));
+            auto_ptr_char p2(e->getAttributeNS(NULL,sslport));
+            if (n.get()) m_name=n.get();
+            if (s.get()) m_scheme=s.get();
+            if (p.get()) m_port=p.get();
+            if (p2.get()) m_sslport=p2.get();
+            e = XMLHelper::getFirstChildElement(e, Alias);
+            while (e) {
+                if (e->hasChildNodes()) {
+                    auto_ptr_char alias(e->getFirstChild()->getNodeValue());
+                    m_aliases.insert(alias.get());
+                }
+                e = XMLHelper::getNextSiblingElement(e, Alias);
+            }
         }
-        else if (!strcmp("PBinding0",token))
-               binding=auto_ptr<XMLCh>(XMLString::transcode(w));
-        else if (!strcmp("LBinding0",token))
-               location=auto_ptr<XMLCh>(XMLString::transcode(w));
-        else if (!strcmp("Time",token))
-               m_sessionCreated=atoi(w);
-        else if (!strcmp("ClientAddress",token))
-               m_clientAddress=w;
-        else if (!strcmp("EOF",token))
-               break;
-    }
-    fclose(f);
+        string m_scheme,m_port,m_sslport,m_name;
+        set<string> m_aliases;
+    };
+
+    struct context_t {
+       char* m_user;
+       bool m_checked;
+    };
     
-    if (binding.get()!=NULL && location.get()!=NULL)
-        m_binding=new SAMLAuthorityBinding(g_authorityKind,binding.get(),location.get());
-
-    m_lastAccess=time(NULL);
-    if (!m_sessionCreated)
-        m_sessionCreated=m_lastAccess;
-}
-
-CCacheEntry::~CCacheEntry()
-{
-    delete m_binding;
-    delete m_response;
-    delete[] m_serialized;
-}
-
-bool CCacheEntry::isSessionValid(time_t lifetime, time_t timeout)
-{
-    time_t now=time(NULL);
-    if (lifetime > 0 && now > m_sessionCreated+lifetime)
-        return false;
-    if (timeout > 0 && now-m_lastAccess >= timeout)
-        return false;
-    m_lastAccess=now;
-    return true;
+    HINSTANCE g_hinstDLL;
+    SPConfig* g_Config = NULL;
+    map<string,site_t> g_Sites;
+    bool g_bNormalizeRequest = true;
+    string g_unsetHeaderValue;
+    bool g_checkSpoofing = true;
+    bool g_catchAll = false;
+    vector<string> g_NoCerts;
 }
 
-Iterator<SAMLAttribute*> CCacheEntry::getAttributes(const char* resource_url, settings_t* pSite)
+BOOL LogEvent(
+    LPCSTR  lpUNCServerName,
+    WORD  wType,
+    DWORD  dwEventID,
+    PSID  lpUserSid,
+    LPCSTR  message)
 {
-    populate(resource_url,pSite);
-    if (m_assertion)
-    {
-        Iterator<SAMLStatement*> i=m_assertion->getStatements();
-        if (i.hasNext())
-        {
-            SAMLAttributeStatement* s=dynamic_cast<SAMLAttributeStatement*>(i.next());
-            if (s)
-                return s->getAttributes();
-        }
-    }
-    return Iterator<SAMLAttribute*>();
-}
-
-const XMLByte* CCacheEntry::getSerializedAssertion(const char* resource_url, settings_t* pSite)
-{
-    populate(resource_url,pSite);
-    if (m_serialized)
-        return m_serialized;
-    if (!m_assertion)
-        return NULL;
-    ostrstream os;
-    os << *m_assertion;
-    unsigned int outlen;
-    return m_serialized=Base64::encode(reinterpret_cast<XMLByte*>(os.str()),os.pcount(),&outlen);
+    LPCSTR  messages[] = {message, NULL};
+    
+    HANDLE hElog = RegisterEventSource(lpUNCServerName, "Shibboleth ISAPI Filter");
+    BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, NULL);
+    return (DeregisterEventSource(hElog) && res);
 }
 
-void CCacheEntry::populate(const char* resource_url, settings_t* pSite)
+extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
 {
-#undef FUNC
-#define FUNC populate
-    Category& log=Category::getInstance("isapi_shib.CCacheEntry");
-
-    // Can we use what we have?
-    if (m_assertion && m_assertion->getNotOnOrAfter())
-    {
-        // This is awful, but the XMLDateTime class is truly horrible.
-        time_t now=time(NULL);
-        struct tm* ptime=gmtime(&now);
-        char timebuf[32];
-        strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
-        auto_ptr<XMLCh> timeptr(XMLString::transcode(timebuf));
-        XMLDateTime curDateTime(timeptr.get());
-        int result=XMLDateTime::compareOrder(&curDateTime,m_assertion->getNotOnOrAfter());
-        if (XMLDateTime::LESS_THAN)
-            return;
-
-        delete m_response;
-        delete[] m_serialized;
-        m_assertion=NULL;
-        m_response=NULL;
-        m_serialized=NULL;
-
-        log.info("%s: cached attributes have expired",FUNC);
-    }
-
-    if (!m_binding)
-        return;
-
-    auto_ptr<XMLCh> resource(XMLString::transcode(resource_url));
-
-    // Build a SAML Request and send it to the AA.
-    SAMLSubject* subject=new SAMLSubject(m_handle.c_str(),m_originSite.c_str());
-    SAMLAttributeQuery* q=new SAMLAttributeQuery(subject,resource.get());
-    SAMLRequest* req=new SAMLRequest(q,ArrayIterator<saml::QName>(&g_respondWith));
-    SAMLBinding* pBinding=pSite->g_AuthCache.getBinding(m_binding->getBinding());
-    m_response=pBinding->send(*m_binding,*req);
-    delete req;
-
-    // Store off the assertion for quick access. Memory mgmt is based on the response pointer.
-    Iterator<SAMLAssertion*> i=m_response->getAssertions();
-    if (i.hasNext())
-        m_assertion=i.next();
-
-    auto_ptr<char> h(XMLString::transcode(m_handle.c_str()));
-    auto_ptr<char> d(XMLString::transcode(m_originSite.c_str()));
-    log.info("%s: fetched and stored SAML response for %s@%s",FUNC,h.get(),d.get());
+    if (fdwReason==DLL_PROCESS_ATTACH)
+        g_hinstDLL=hinstDLL;
+    return TRUE;
 }
 
-class DummyMapper : public IOriginSiteMapper
-{
-public:
-    DummyMapper() { InitializeCriticalSection(&m_lock); }
-    ~DummyMapper();
-    virtual Iterator<xstring> getHandleServiceNames(const XMLCh* originSite) { return Iterator<xstring>(); }
-    virtual Key* getHandleServiceKey(const XMLCh* handleService) { return NULL; }
-    virtual Iterator<xstring> getSecurityDomains(const XMLCh* originSite);
-    virtual Iterator<X509Certificate*> getTrustedRoots() { return Iterator<X509Certificate*>(); }
-
-private:
-    typedef map<xstring,vector<xstring>*> domains_t;
-    domains_t m_domains;
-    CRITICAL_SECTION m_lock;
-};
-
-Iterator<xstring> DummyMapper::getSecurityDomains(const XMLCh* originSite)
+extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
 {
-    EnterCriticalSection(&m_lock);
-    vector<xstring>* pv=NULL;
-    domains_t::iterator i=m_domains.find(originSite);
-    if (i==m_domains.end())
-    {
-        pv=new vector<xstring>();
-        pv->push_back(originSite);
-        pair<domains_t::iterator,bool> p=m_domains.insert(domains_t::value_type(originSite,pv));
-           i=p.first;
+    if (!pVer)
+        return FALSE;
+        
+    if (!g_Config) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Extension mode startup not possible, is the DLL loaded as a filter?");
+        return FALSE;
     }
-    else
-        pv=i->second;
-    LeaveCriticalSection(&m_lock);
-    return Iterator<xstring>(*pv);
-}
 
-DummyMapper::~DummyMapper()
-{
-    for (domains_t::iterator i=m_domains.begin(); i!=m_domains.end(); i++)
-        delete i->second;
-    DeleteCriticalSection(&m_lock);
+    pVer->dwExtensionVersion=HSE_VERSION;
+    strncpy(pVer->lpszExtensionDesc,"Shibboleth ISAPI Extension",HSE_MAX_EXT_DLL_NAME_LEN-1);
+    return TRUE;
 }
 
-// globals
-HINSTANCE g_hinstDLL;
-ULONG g_ulMaxSite=1;                        // max IIS site instance to handle
-settings_t* g_Sites=NULL;                   // array of site settings
-map<string,string> g_mapAttribNameToHeader; // attribute mapping
-map<xstring,string> g_mapAttribNames;
-
-
-extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
+extern "C" BOOL WINAPI TerminateExtension(DWORD)
 {
-    if (fdwReason==DLL_PROCESS_ATTACH)
-        g_hinstDLL=hinstDLL;
-    return TRUE;
+    return TRUE;    // cleanup should happen when filter unloads
 }
 
 extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
 {
     if (!pVer)
         return FALSE;
+    else if (g_Config) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Reentrant filter initialization, ignoring...");
+        return TRUE;
+    }
 
-    // Get module pathname and replace file name with ini file name.
-    char inifile[MAX_PATH+1];
-    if (GetModuleFileName(g_hinstDLL,inifile,MAX_PATH+1)==0)
-        return FALSE;
-    char* pch=strrchr(inifile,'\\');
-    if (pch==NULL)
+    g_Config=&SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging |
+        SPConfig::Handlers
+        );
+    if (!g_Config->init()) {
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed during library initialization, check native log for help.");
         return FALSE;
-    pch++;
-    *pch=0;
-    strcat(inifile,"isapi_shib.ini");
-
-    // Read system-wide parameters from isapi_shib.ini.
-    char buf[1024];
-    char buf3[48];
-
-    try
-    {
-        SAMLConfig& SAMLconf=SAMLConfig::getConfig();
-        
-        GetPrivateProfileString("shibboleth","ShibLogConfig","",buf,sizeof(buf),inifile);
-        if (*buf)
-            PropertyConfigurator::configure(buf);
-        Category& log=Category::getInstance("isapi_shib.GetFilterVersion");
-        log.info("using INI file: %s",inifile);
-
-        GetPrivateProfileString("shibboleth","ShibSchemaPath","",buf,sizeof(buf),inifile);
-        if (!*buf)
-        {
-            log.fatal("ShibSchemaPath missing");
-            return FALSE;
-        }
-        SAMLconf.schema_dir=buf;
-        if (*SAMLconf.schema_dir.end()!='\\')
-            SAMLconf.schema_dir+='\\';
-
-        GetPrivateProfileString("shibboleth","ShibSSLCertFile","",buf,sizeof(buf),inifile);
-        if (!*buf)
-        {
-            log.fatal("ShibSSLCertFile missing");
-            return FALSE;
-        }
-        SAMLconf.ssl_certfile=buf;
-
-        GetPrivateProfileString("shibboleth","ShibSSLKeyFile","",buf,sizeof(buf),inifile);
-        if (!*buf)
-        {
-            log.fatal("ShibSSLKeyFile missing");
-            return FALSE;
-        }
-        SAMLconf.ssl_keyfile=buf;
-
-        GetPrivateProfileString("shibboleth","ShibSSLKeyPass","",buf,sizeof(buf),inifile);
-        SAMLconf.ssl_keypass=buf;
-
-        GetPrivateProfileString("shibboleth","ShibSSLCAList","",buf,sizeof(buf),inifile);
-        SAMLconf.ssl_calist=buf;
-
-        // Read site count and allocate site array.
-        g_ulMaxSite=GetPrivateProfileInt("shibboleth","max-site",0,inifile);
-        if (g_ulMaxSite==0)
-        {
-            log.fatal("max-site was 0 or invalid");
-            return FALSE;
-        }
-        log.debug("max-site is %d",g_ulMaxSite);
-        g_Sites=new settings_t[g_ulMaxSite];
-
-        // Read site-specific settings for each site.
-        for (ULONG i=0; i<g_ulMaxSite; i++)
-        {
-            ultoa(i+1,buf3,10);
-            GetPrivateProfileString(buf3,"ShibSiteName","X",buf,sizeof(buf),inifile);
-            if (!strcmp(buf,"X"))
-            {
-                log.info("skipping site %d (no ShibSiteName)",i);
-                continue;
-            }
-
-            GetPrivateProfileString(buf3,"ShibCookieName","",buf,sizeof(buf),inifile);
-            if (!*buf)
-            {
-                delete[] g_Sites;
-                log.fatal("ShibCookieName missing in site %d",i);
-                return FALSE;
-            }
-            g_Sites[i].g_CookieName=buf;
-
-            GetPrivateProfileString(buf3,"WAYFLocation","",buf,sizeof(buf),inifile);
-            if (!*buf)
-            {
-                delete[] g_Sites;
-                log.fatal("WAYFLocation missing in site %d",i);
-                return FALSE;
-            }
-            g_Sites[i].g_WAYFLocation=buf;
-
-            GetPrivateProfileString(buf3,"GarbageCollector","",buf,sizeof(buf),inifile);
-            if (!*buf)
-            {
-                delete[] g_Sites;
-                log.fatal("GarbageCollector missing in site %d",i);
-                return FALSE;
-            }
-            g_Sites[i].g_GarbageCollector=buf;
-
-            GetPrivateProfileString(buf3,"SHIRELocation","",buf,sizeof(buf),inifile);
-            if (!*buf)
-            {
-                delete[] g_Sites;
-                log.fatal("SHIRELocation missing in site %d",i);
-                return FALSE;
-            }
-            g_Sites[i].g_SHIRELocation=buf;
-
-            GetPrivateProfileString(buf3,"SHIRESessionPath","",buf,sizeof(buf),inifile);
-            if (!*buf)
-            {
-                delete[] g_Sites;
-                log.fatal("SHIRESessionPath missing in site %d",i);
-                return FALSE;
-            }
-            g_Sites[i].g_SHIRESessionPath=buf;
-            if (g_Sites[i].g_SHIRESessionPath[g_Sites[i].g_SHIRESessionPath.length()]!='\\')
-                g_Sites[i].g_SHIRESessionPath+='\\';
-
-            // Old-style matching string.
-            GetPrivateProfileString(buf3,"ShibMustContain","",buf,sizeof(buf),inifile);
-            _strupr(buf);
-            char* start=buf;
-            while (char* sep=strchr(start,';'))
-            {
-                *sep='\0';
-                if (*start)
-                {
-                    g_Sites[i].g_MustContain.push_back(start);
-                    log.info("site %d told to match against %s",i,start);
-                }
-                start=sep+1;
-            }
-            if (*start)
-            {
-                g_Sites[i].g_MustContain.push_back(start);
-                log.info("site %d told to match against %s",i,start);
-            }
-            
-            if (GetPrivateProfileInt(buf3,"ShibSSLOnly",1,inifile)==0)
-                g_Sites[i].g_bSSLOnly=false;
-            if (GetPrivateProfileInt(buf3,"ShibCheckAddress",1,inifile)==0)
-                g_Sites[i].g_bCheckAddress=false;
-            if (GetPrivateProfileInt(buf3,"ShibExportAssertion",0,inifile)==1)
-                g_Sites[i].g_bExportAssertion=true;
-            g_Sites[i].g_Lifetime=GetPrivateProfileInt(buf3,"ShibAuthLifetime",7200,inifile);
-            if (g_Sites[i].g_Lifetime<=0)
-                g_Sites[i].g_Lifetime=7200;
-            g_Sites[i].g_Timeout=GetPrivateProfileInt(buf3,"ShibAuthTimeout",3600,inifile);
-            if (g_Sites[i].g_Timeout<=0)
-                g_Sites[i].g_Timeout=3600;
-            log.info("configuration of site %d complete",i);
-        }
-
-        ShibConfig& Shibconf=ShibConfig::getConfig();
-        static DummyMapper mapper;
-
-        if (!SAMLconf.init())
-        {
-            delete[] g_Sites;
-            log.fatal("SAML initialization failed");
-            return FALSE;
-        }
-
-        Shibconf.origin_mapper=&mapper;
-        if (!Shibconf.init())
-        {
-            delete[] g_Sites;
-            log.fatal("Shibboleth initialization failed");
-            return FALSE;
-        }
-
-        char buf2[32767];
-        DWORD res=GetPrivateProfileSection("ShibMapAttributes",buf2,sizeof(buf2),inifile);
-        if (res==sizeof(buf2)-2)
-        {
-            delete[] g_Sites;
-            log.fatal("ShibMapAttributes INI section was larger than 32k");
-            return FALSE;
-        }
-
-        for (char* attr=buf2; *attr; attr++)
-        {
-            char* delim=strchr(attr,'=');
-            if (!delim)
-            {
-                delete[] g_Sites;
-                log.fatal("unrecognizable ShibMapAttributes directive: %s",attr);
-                return FALSE;
-            }
-            *delim++=0;
-            g_mapAttribNameToHeader[attr]=(string(delim) + ':');
-            log.info("mapping attribute %s to request header %s",attr,delim);
-            attr=delim + strlen(delim);
-        }
+    }
 
-        log.info("configuration of attributes complete");
+    LPCSTR config=getenv("SHIBSP_CONFIG");
+    if (!config)
+        config=SHIBSP_CONFIG;
 
-        // Transcode the attribute names we know about for quick handling map access.
-        for (map<string,string>::const_iterator j=g_mapAttribNameToHeader.begin();
-             j!=g_mapAttribNameToHeader.end(); j++)
-        {
-            auto_ptr<XMLCh> temp(XMLString::transcode(j->first.c_str()));
-            g_mapAttribNames[temp.get()]=j->first;
-        }
+    try {
+        DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
+        XercesJanitor<DOMDocument> docjanitor(dummydoc);
+        DOMElement* dummy = dummydoc->createElementNS(NULL,path);
+        auto_ptr_XMLCh src(config);
+        dummy->setAttributeNS(NULL,path,src.get());
+        dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
 
-        res=GetPrivateProfileSection("ShibExtensions",buf2,sizeof(buf2),inifile);
-        if (res==sizeof(buf2)-2)
-        {
-            delete[] g_Sites;
-            log.fatal("ShibExtensions INI section was larger than 32k");
-            return FALSE;
-        }
-
-        for (char* libpath=buf2; *libpath; libpath+=strlen(libpath)+1)
-            SAMLconf.saml_register_extension(libpath);
-
-        log.info("completed loading of extension libraries");
-    }
-    catch (bad_alloc)
-    {
-        delete[] g_Sites;
-        Category::getInstance("isapi_shib.GetFilterVersion").fatal("out of memory");
-        return FALSE;
+        g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
+        g_Config->getServiceProvider()->init();
     }
-    catch (log4cpp::ConfigureFailure& ex)
-    {
-        delete[] g_Sites;
-        WritePrivateProfileString("startlog","bailed-at","log4cpp exception caught",inifile);
-        WritePrivateProfileString("startlog","log4cpp",ex.what(),inifile);
+    catch (exception& ex) {
+        g_Config->term();
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, ex.what());
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed to load configuration, check native log for details.");
         return FALSE;
     }
-    catch (SAMLException& ex)
-    {
-        delete[] g_Sites;
-        Category::getInstance("isapi_shib.GetFilterVersion").fatal("caught SAML exception: %s",ex.what());
-        return FALSE;
+    
+    // Access implementation-specifics and site mappings.
+    ServiceProvider* sp=g_Config->getServiceProvider();
+    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;
+        flag=props->getBool("catchAll");
+        g_catchAll = flag.first && flag.second;
+
+        props = props->getPropertySet("ISAPI");
+        if (props) {
+            flag = props->getBool("normalizeRequest");
+            g_bNormalizeRequest = !flag.first || flag.second;
+            const DOMElement* child = XMLHelper::getFirstChildElement(props->getElement(),Site);
+            while (child) {
+                auto_ptr_char id(child->getAttributeNS(NULL,id));
+                if (id.get())
+                    g_Sites.insert(pair<string,site_t>(id.get(),site_t(child)));
+                child=XMLHelper::getNextSiblingElement(child,Site);
+            }
+        }
     }
 
     pVer->dwFilterVersion=HTTP_FILTER_REVISION;
@@ -684,17 +230,16 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
                    SF_NOTIFY_NONSECURE_PORT |
                    SF_NOTIFY_PREPROC_HEADERS |
                    SF_NOTIFY_LOG);
+    LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter initialized...");
     return TRUE;
 }
 
-extern "C" BOOL WINAPI TerminateFilter(DWORD dwFlags)
+extern "C" BOOL WINAPI TerminateFilter(DWORD)
 {
-    Category::getInstance("isapi_shib.TerminateFilter").info("shutting down...");
-    delete[] g_Sites;
-    g_Sites=NULL;
-    ShibConfig::getConfig().term();
-    SAMLConfig::getConfig().term();
-    Category::getInstance("isapi_shib.TerminateFilter").info("shut down complete");
+    if (g_Config)
+        g_Config->term();
+    g_Config = NULL;
+    LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter shut down...");
     return TRUE;
 }
 
@@ -718,7 +263,7 @@ public:
     size_t size() const { return buflen; }
     bool empty() const { return length()==0; }
     void reserve(size_t s, bool keep=false);
-    void erase() { if (bufptr) *bufptr=0; }
+    void erase() { if (bufptr) memset(bufptr,0,buflen); }
     operator char*() { return bufptr; }
     bool operator ==(const char* s) const;
     bool operator !=(const char* s) const { return !(*this==s); }
@@ -748,16 +293,13 @@ bool dynabuf::operator==(const char* s) const
         return strcmp(bufptr,s)==0;
 }
 
-void GetServerVariable(PHTTP_FILTER_CONTEXT pfc,
-                       LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
-    throw (bad_alloc, DWORD)
+void GetServerVariable(PHTTP_FILTER_CONTEXT pfc, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
 {
-    s.erase();
     s.reserve(size);
+    s.erase();
     size=s.size();
 
-    while (!pfc->GetServerVariable(pfc,lpszVariable,s,&size))
-    {
+    while (!pfc->GetServerVariable(pfc,lpszVariable,s,&size)) {
         // Grumble. Check the error.
         DWORD e=GetLastError();
         if (e==ERROR_INSUFFICIENT_BUFFER)
@@ -769,16 +311,13 @@ void GetServerVariable(PHTTP_FILTER_CONTEXT pfc,
         throw ERROR_NO_DATA;
 }
 
-void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
-               LPSTR lpszName, dynabuf& s, DWORD size=80, bool bRequired=true)
-    throw (bad_alloc, DWORD)
+void GetServerVariable(LPEXTENSION_CONTROL_BLOCK lpECB, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
 {
-    s.erase();
     s.reserve(size);
+    s.erase();
     size=s.size();
 
-    while (!pn->GetHeader(pfc,lpszName,s,&size))
-    {
+    while (!lpECB->GetServerVariable(lpECB->ConnID,lpszVariable,s,&size)) {
         // Grumble. Check the error.
         DWORD e=GetLastError();
         if (e==ERROR_INSUFFICIENT_BUFFER)
@@ -790,68 +329,225 @@ void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
         throw ERROR_NO_DATA;
 }
 
-inline char hexchar(unsigned short s)
+void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
+               LPSTR lpszName, dynabuf& s, DWORD size=80, bool bRequired=true)
 {
-    return (s<=9) ? ('0' + s) : ('A' + s - 10);
-}
+    s.reserve(size);
+    s.erase();
+    size=s.size();
 
-string url_encode(const char* url) throw (bad_alloc)
-{
-    static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
-    string s;
-    for (const char* pch=url; *pch; pch++)
-    {
-        if (strchr(badchars,*pch)!=NULL || *pch<=0x1F || *pch>=0x7F)
-            s=s + '%' + hexchar(*pch >> 4) + hexchar(*pch & 0x0F);
+    while (!pn->GetHeader(pfc,lpszName,s,&size)) {
+        // Grumble. Check the error.
+        DWORD e=GetLastError();
+        if (e==ERROR_INSUFFICIENT_BUFFER)
+            s.reserve(size);
         else
-            s+=*pch;
+            break;
     }
-    return s;
+    if (bRequired && s.empty())
+        throw ERROR_NO_DATA;
 }
 
-string get_target(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, settings_t* pSite)
-{
-    // Reconstructing the requested URL is not fun. Apparently, the PREPROC_HEADERS
-    // event means way pre. As in, none of the usual CGI headers are in place yet.
-    // It's actually almost easier, in a way, because all the path-info and query
-    // stuff is in one place, the requested URL, which we can get. But we have to
-    // reconstruct the protocol/host pair using tweezers.
-    string s;
-    if (pfc->fIsSecurePort)
-        s="https://";
-    else
-        s="http://";
+/****************************************************************************/
+// ISAPI Filter
 
-    dynabuf buf(256);
-    GetServerVariable(pfc,"SERVER_NAME",buf);
-    s+=buf;
-
-    GetServerVariable(pfc,"SERVER_PORT",buf,10);
-    if (buf!=(pfc->fIsSecurePort ? "443" : "80"))
-        s=s + ':' + static_cast<char*>(buf);
+class ShibTargetIsapiF : public AbstractSPRequest
+{
+  PHTTP_FILTER_CONTEXT m_pfc;
+  PHTTP_FILTER_PREPROC_HEADERS m_pn;
+  multimap<string,string> m_headers;
+  int m_port;
+  string m_scheme,m_hostname;
+  mutable string m_remote_addr,m_content_type,m_method;
+  dynabuf m_allhttp;
 
-    GetHeader(pn,pfc,"url",buf,256,false);
-    s+=buf;
+public:
+  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site)
+      : AbstractSPRequest(SHIBSP_LOGCAT".ISAPI"), m_pfc(pfc), m_pn(pn), m_allhttp(4096) {
+
+    // URL path always come from IIS.
+    dynabuf var(256);
+    GetHeader(pn,pfc,"url",var,256,false);
+    setRequestURI(var);
+
+    // Port may come from IIS or from site def.
+    if (!g_bNormalizeRequest || (pfc->fIsSecurePort && site.m_sslport.empty()) || (!pfc->fIsSecurePort && site.m_port.empty())) {
+        GetServerVariable(pfc,"SERVER_PORT",var,10);
+        m_port = atoi(var);
+    }
+    else if (pfc->fIsSecurePort) {
+        m_port = atoi(site.m_sslport.c_str());
+    }
+    else {
+        m_port = atoi(site.m_port.c_str());
+    }
+    
+    // Scheme may come from site def or be derived from IIS.
+    m_scheme=site.m_scheme;
+    if (m_scheme.empty() || !g_bNormalizeRequest)
+        m_scheme=pfc->fIsSecurePort ? "https" : "http";
 
-    return s;
-}
+    GetServerVariable(pfc,"SERVER_NAME",var,32);
 
-string get_shire_location(PHTTP_FILTER_CONTEXT pfc, settings_t* pSite, const char* target)
-{
-    if (pSite->g_SHIRELocation[0]!='/')
-        return url_encode(pSite->g_SHIRELocation.c_str());
-    const char* colon=strchr(target,':');
-    const char* slash=strchr(colon+3,'/');
-    string s(target,slash-target);
-    s+=pSite->g_SHIRELocation;
-    return url_encode(s.c_str());
-}
+    // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
+    m_hostname = var;
+    if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+        m_hostname=site.m_name;
+    
+    if (!pfc->pFilterContext) {
+        pfc->pFilterContext = pfc->AllocMem(pfc, sizeof(context_t), NULL);
+        if (static_cast<context_t*>(pfc->pFilterContext)) {
+            static_cast<context_t*>(pfc->pFilterContext)->m_user = NULL;
+            static_cast<context_t*>(pfc->pFilterContext)->m_checked = false;
+        }
+    }    
+  }
+  ~ShibTargetIsapiF() { }
+
+  const char* getScheme() const {
+    return m_scheme.c_str();
+  }
+  const char* getHostname() const {
+    return m_hostname.c_str();
+  }
+  int getPort() const {
+    return m_port;
+  }
+  const char* getMethod() const {
+    if (m_method.empty()) {
+        dynabuf var(5);
+        GetServerVariable(m_pfc,"REQUEST_METHOD",var,5,false);
+        if (!var.empty())
+            m_method = var;
+    }
+    return m_method.c_str();
+  }
+  string getContentType() const {
+    if (m_content_type.empty()) {
+        dynabuf var(32);
+        GetServerVariable(m_pfc,"CONTENT_TYPE",var,32,false);
+        if (!var.empty())
+            m_content_type = var;
+    }
+    return m_content_type;
+  }
+  long getContentLength() const {
+      return 0;
+  }
+  string getRemoteAddr() const {
+    if (m_remote_addr.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_pfc,"REMOTE_ADDR",var,16,false);
+        if (!var.empty())
+            m_remote_addr = var;
+    }
+    return m_remote_addr;
+  }
+  void log(SPLogLevel level, const string& msg) {
+    AbstractSPRequest::log(level,msg);
+    if (level >= SPError)
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
+  }
+  void clearHeader(const char* rawname, const char* cginame) {
+       if (g_checkSpoofing && m_pfc->pFilterContext && !static_cast<context_t*>(m_pfc->pFilterContext)->m_checked) {
+        if (m_allhttp.empty())
+               GetServerVariable(m_pfc,"ALL_HTTP",m_allhttp,4096);
+        if (strstr(m_allhttp, cginame))
+            throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
+    }
+    string hdr(!strcmp(rawname,"REMOTE_USER") ? "remote-user" : rawname);
+    hdr += ':';
+    m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(g_unsetHeaderValue.c_str()));
+  }
+  void setHeader(const char* name, const char* value) {
+    string hdr(name);
+    hdr += ':';
+    m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(value));
+  }
+  string getHeader(const char* name) const {
+    string hdr(name);
+    hdr += ':';
+    dynabuf buf(256);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 256, false);
+    return string(buf);
+  }
+  void setRemoteUser(const char* user) {
+    setHeader("remote-user", user);
+    if (m_pfc->pFilterContext) {
+        if (!user || !*user)
+            static_cast<context_t*>(m_pfc->pFilterContext)->m_user = NULL;
+        else if (static_cast<context_t*>(m_pfc->pFilterContext)->m_user = (char*)m_pfc->AllocMem(m_pfc, sizeof(char) * (strlen(user) + 1), NULL))
+            strcpy(static_cast<context_t*>(m_pfc->pFilterContext)->m_user, user);
+    }
+  }
+  string getRemoteUser() const {
+    return getHeader("remote-user");
+  }
+  void setResponseHeader(const char* name, const char* value) {
+    // Set for later.
+    if (value)
+        m_headers.insert(make_pair(name,value));
+    else
+        m_headers.erase(name);
+  }
+  long sendResponse(istream& in, long status) {
+    string hdr = string("Connection: close\r\n");
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+        hdr += i->first + ": " + i->second + "\r\n";
+    hdr += "\r\n";
+    const char* codestr="200 OK";
+    switch (status) {
+        case XMLTOOLING_HTTP_STATUS_UNAUTHORIZED:   codestr="401 Authorization Required"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:      codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND:       codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:          codestr="500 Server Error"; break;
+    }
+    m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, (void*)codestr, (DWORD)hdr.c_str(), 0);
+    char buf[1024];
+    while (in) {
+        in.read(buf,1024);
+        DWORD resplen = in.gcount();
+        m_pfc->WriteClient(m_pfc, buf, &resplen, 0);
+    }
+    return SF_STATUS_REQ_FINISHED;
+  }
+  long sendRedirect(const char* url) {
+    // XXX: Don't support the httpRedirect option, yet.
+    string hdr=string("Location: ") + url + "\r\n"
+      "Content-Type: text/html\r\n"
+      "Content-Length: 40\r\n"
+      "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
+      "Cache-Control: private,no-store,no-cache\r\n";
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+        hdr += i->first + ": " + i->second + "\r\n";
+    hdr += "\r\n";
+    m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, "302 Please Wait", (DWORD)hdr.c_str(), 0);
+    static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+    DWORD resplen=40;
+    m_pfc->WriteClient(m_pfc, (LPVOID)redmsg, &resplen, 0);
+    return SF_STATUS_REQ_FINISHED;
+  }
+  long returnDecline() {
+      return SF_STATUS_REQ_NEXT_NOTIFICATION;
+  }
+  long returnOK() {
+    return SF_STATUS_REQ_NEXT_NOTIFICATION;
+  }
+
+  const vector<string>& getClientCertificates() const {
+      return g_NoCerts;
+  }
+  
+  // The filter never processes the POST, so stub these methods.
+  const char* getQueryString() const { throw IOException("getQueryString not implemented"); }
+  const char* getRequestBody() const { throw IOException("getRequestBody not implemented"); }
+};
 
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
 {
-    Category::getInstance("isapi_shib.WriteClientError").error("sending error page to browser: %s",msg);
-
-    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
+    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)ctype,0);
     static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Filter Error</TITLE></HEAD><BODY>"
                             "<H1>Shibboleth Filter Error</H1>";
     DWORD resplen=strlen(xmsg);
@@ -864,343 +560,390 @@ DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
     return SF_STATUS_REQ_FINISHED;
 }
 
-DWORD shib_shar_error(PHTTP_FILTER_CONTEXT pfc, SAMLException& e)
-{
-    Category::getInstance("isapi_shib.shib_shar_error").errorStream()
-        << "exception during SHAR request: " << e;
-
-    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
-    
-    static const char* msg="<HTML><HEAD><TITLE>Shibboleth Attribute Exchange Failed</TITLE></HEAD>\n"
-                           "<BODY><H3>Shibboleth Attribute Exchange Failed</H3>\n"
-                           "While attempting to securely contact your origin site to obtain "
-                           "information about you, an error occurred:<BR><BLOCKQUOTE>";
-    DWORD resplen=strlen(msg);
-    pfc->WriteClient(pfc,(LPVOID)msg,&resplen,0);
-
-    const char* msg2=e.what();
-    resplen=strlen(msg2);
-    pfc->WriteClient(pfc,(LPVOID)msg2,&resplen,0);
-
-    bool origin=true;
-    Iterator<saml::QName> i=e.getCodes();
-    if (i.hasNext() && XMLString::compareString(L(Responder),i.next().getLocalName()))
-        origin=false;
-
-    const char* msg4=(origin ? "</BLOCKQUOTE><P>The error appears to be located at your origin site.<BR>" :
-                               "</BLOCKQUOTE><P>The error appears to be located at the resource provider's site.<BR>");
-    resplen=strlen(msg4);
-    pfc->WriteClient(pfc,(LPVOID)msg4,&resplen,0);
-    
-    static const char* msg5="<P>Try restarting your browser and accessing the site again to make "
-                            "sure the problem isn't temporary. Please contact the administrator "
-                            "of that site if this problem recurs. If possible, provide him/her "
-                            "with the error message shown above.</BODY></HTML>";
-    resplen=strlen(msg5);
-    pfc->WriteClient(pfc,(LPVOID)msg5,&resplen,0);
-    return SF_STATUS_REQ_FINISHED;
-}
-
 extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification)
 {
     // Is this a log notification?
     if (notificationType==SF_NOTIFY_LOG)
     {
         if (pfc->pFilterContext)
-            ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast<LPCSTR>(pfc->pFilterContext);
+               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast<context_t*>(pfc->pFilterContext)->m_user;
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
 
-    char* xmsg=NULL;
-    settings_t* pSite=NULL;
-    bool bLocked=false;
     PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification;
-    Category& log=Category::getInstance("isapi_shib.HttpFilterProc");
     try
     {
-        // Determine web site number.
+        // Determine web site number. This can't really fail, I don't think.
         dynabuf buf(128);
-        ULONG site_id=0;
         GetServerVariable(pfc,"INSTANCE_ID",buf,10);
-        if ((site_id=strtoul(buf,NULL,10))==0)
-            return WriteClientError(pfc,"IIS site instance appears to be invalid.");
 
-        // Match site instance to site settings pointer.
-        if (site_id>g_ulMaxSite || g_Sites[site_id-1].g_CookieName.empty())
+        // Match site instance to host name, skip if no match.
+        map<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
+        if (map_i==g_Sites.end())
             return SF_STATUS_REQ_NEXT_NOTIFICATION;
-        pSite=&g_Sites[site_id-1];
+            
+        ostringstream threadid;
+        threadid << "[" << getpid() << "] isapi_shib" << '\0';
+        xmltooling::NDC ndc(threadid.str().c_str());
 
-        string targeturl=get_target(pfc,pn,pSite);
+        ShibTargetIsapiF stf(pfc, pn, map_i->second);
 
-        // If the user is accessing the SHIRE acceptance point, pass on.
-        if (targeturl.find(pSite->g_SHIRELocation)!=string::npos)
-        {
-            log.debug("passing on SHIRE acceptance request");
-            return SF_STATUS_REQ_NEXT_NOTIFICATION;
-        }
+        // "false" because we don't override the Shib settings
+        pair<bool,long> res = stf.getServiceProvider().doAuthentication(stf);
+        if (pfc->pFilterContext)
+            static_cast<context_t*>(pfc->pFilterContext)->m_checked = true;
+        if (res.first) return res.second;
 
-        // If this is the garbage collection service, do a cache sweep.
-        if (targeturl==pSite->g_GarbageCollector)
-        {
-            log.notice("garbage collector triggered");
-            pSite->g_AuthCache.lock();
-            bLocked=true;
-            pSite->g_AuthCache.sweep(pSite->g_Lifetime);
-            pSite->g_AuthCache.unlock();
-            bLocked=false;
-            return WriteClientError(pfc,"The cache was swept for expired sessions.");
-        }
+        // "false" because we don't override the Shib settings
+        res = stf.getServiceProvider().doExport(stf);
+        if (res.first) return res.second;
 
-        // Get the url request and scan for the must-contain string.
-        if (!pSite->g_MustContain.empty())
-        {
-            char* upcased=new char[targeturl.length()+1];
-            strcpy(upcased,targeturl.c_str());
-            _strupr(upcased);
-            for (vector<string>::const_iterator index=pSite->g_MustContain.begin(); index!=pSite->g_MustContain.end(); index++)
-                if (strstr(upcased,index->c_str()))
-                    break;
-            delete[] upcased;
-            if (index==pSite->g_MustContain.end())
-                return SF_STATUS_REQ_NEXT_NOTIFICATION;
-        }
+        res = stf.getServiceProvider().doAuthorization(stf);
+        if (res.first) return res.second;
 
-        // SSL check.
-        if (pSite->g_bSSLOnly && !pfc->fIsSecurePort)
-        {
-            log.warn("blocking non-SSL request");
-            xmsg="<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD><BODY>"
-                 "<H1>Access Denied</H1>"
-                 "This server is configured to deny non-SSL requests for secure resources. "
-                 "Try your request again using https instead of http."
-                 "</BODY></HTML>";
-            DWORD resplen=strlen(xmsg);
-            pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
-            pfc->WriteClient(pfc,xmsg,&resplen,0);
-            return SF_STATUS_REQ_FINISHED;
-        }
+        return SF_STATUS_REQ_NEXT_NOTIFICATION;
+    }
+    catch(bad_alloc) {
+        return WriteClientError(pfc,"Out of Memory");
+    }
+    catch(long e) {
+        if (e==ERROR_NO_DATA)
+            return WriteClientError(pfc,"A required variable or header was empty.");
+        else
+            return WriteClientError(pfc,"Shibboleth Filter detected unexpected IIS error.");
+    }
+    catch (exception& e) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+        return WriteClientError(pfc,"Shibboleth Filter caught an exception, check Event Log for details.");
+    }
+    catch(...) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Shibboleth Filter threw an unknown exception.");
+        if (g_catchAll)
+            return WriteClientError(pfc,"Shibboleth Filter threw an unknown exception.");
+        throw;
+    }
 
-        // Check for authentication cookie.
-        const char* session_id=NULL;
-        GetHeader(pn,pfc,"Cookie:",buf,128,false);
-        if (buf.empty() || !(session_id=strstr(buf,pSite->g_CookieName.c_str())) ||
-            *(session_id+pSite->g_CookieName.length())!='=')
-        {
-            log.info("session cookie not found, redirecting to WAYF");
-
-            // Redirect to WAYF.
-            string wayf("Location: ");
-            wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
-                                          "&target=" + url_encode(targeturl.c_str()) + "\r\n";
-            // Insert the headers.
-            pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
-            pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
-            return SF_STATUS_REQ_FINISHED;
-        }
+    return WriteClientError(pfc,"Shibboleth Filter reached unreachable code, save my walrus!");
+}
+        
 
-        session_id+=pSite->g_CookieName.length() + 1;  /* Skip over the '=' */
-        char* cookieend=strchr(session_id,';');
-        if (cookieend)
-            *cookieend = '\0'; /* Ignore anyting after a ; */
-  
-        pSite->g_AuthCache.lock();    // ---> Get cache lock
-        bLocked=true;
+/****************************************************************************/
+// ISAPI Extension
 
-        // The caching logic is the heart of the "SHAR".
-        CCacheEntry* entry=pSite->g_AuthCache.find(session_id);
-        try
-        {
-            if (!entry)
-            {
-                pSite->g_AuthCache.unlock();    // ---> Release cache lock
-                bLocked=false;
-
-                // Construct the path to the session file
-                string sessionFile=pSite->g_SHIRESessionPath + session_id;
-                try
-                {
-                    entry=new CCacheEntry(sessionFile.c_str());
-                }
-                catch (runtime_error e)
-                {
-                    log.info("unable to load session from file '%s', redirecting to WAYF",sessionFile.c_str());
-
-                    // Redirect to WAYF.
-                    string wayf("Location: ");
-                    wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
-                                                  "&target=" + url_encode(targeturl.c_str()) + "\r\n";
-                    wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\r\n";
-
-                    // Insert the headers.
-                    pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
-                    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
-                    return SF_STATUS_REQ_FINISHED;
-                }
-                pSite->g_AuthCache.lock();    // ---> Get cache lock
-                bLocked=true;
-                pSite->g_AuthCache.insert(session_id,entry);
-                log.info("new session established: %s",session_id);
-            }
-            
-            if (!entry->isSessionValid(pSite->g_Lifetime,pSite->g_Timeout))
-            {
-                pSite->g_AuthCache.remove(session_id);
-                pSite->g_AuthCache.unlock();    // ---> Release cache lock
-                bLocked=false;
-                delete entry;
-
-                log.warn("invalidating session because of timeout, redirecting to WAYF");
-
-                // Redirect to WAYF.
-                string wayf("Location: ");
-                wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
-                                              "&target=" + url_encode(targeturl.c_str()) + "\r\n";
-                wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\r\n";
-
-                // Insert the headers.
-                pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
-                pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
-                return SF_STATUS_REQ_FINISHED;
-            }
+DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
+{
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
+    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)ctype);
+    static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Error</TITLE></HEAD><BODY><H1>Shibboleth Error</H1>";
+    DWORD resplen=strlen(xmsg);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg,&resplen,HSE_IO_SYNC);
+    resplen=strlen(msg);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)msg,&resplen,HSE_IO_SYNC);
+    static const char* xmsg2="</BODY></HTML>";
+    resplen=strlen(xmsg2);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg2,&resplen,HSE_IO_SYNC);
+    return HSE_STATUS_SUCCESS;
+}
 
-            if (pSite->g_bCheckAddress && entry->getClientAddress())
-            {
-                GetServerVariable(pfc,"REMOTE_ADDR",buf,16);
-                if (strcmp(entry->getClientAddress(),buf))
-                {
-                    pSite->g_AuthCache.remove(session_id);
-                    delete entry;
-                    pSite->g_AuthCache.unlock();  // ---> Release cache lock
-                    bLocked=false;
-
-                    log.warn("IP address mismatch detected, clearing session");
-
-                    string clearcookie("Set-Cookie: ");
-                    clearcookie+=pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\r\n";
-                    pfc->AddResponseHeaders(pfc,const_cast<char*>(clearcookie.c_str()),0);
-                    return WriteClientError(pfc,
-                        "Your session was terminated because the network address associated "
-                        "with it does not match your current address. This is usually caused "
-                        "by a firewall or proxy of some sort.");
-                }
-            }
 
-            // Clear relevant headers.
-            pn->SetHeader(pfc,"Shib-Attributes:","");
-            pn->SetHeader(pfc,"remote-user:","");
-            for (map<string,string>::const_iterator h_iter=g_mapAttribNameToHeader.begin(); h_iter!=g_mapAttribNameToHeader.end(); h_iter++)
-                if (h_iter->second!="REMOTE_USER:")
-                    pn->SetHeader(pfc,const_cast<char*>(h_iter->second.c_str()),"");
-
-            if (pSite->g_bExportAssertion)
-            {
-                string exp((char*)entry->getSerializedAssertion(targeturl.c_str(),pSite));
-                string::size_type lfeed;
-                while ((lfeed=exp.find('\n'))!=string::npos)
-                    exp.erase(lfeed,1);
-                pn->SetHeader(pfc,"Shib-Attributes:",const_cast<char*>(exp.c_str()));
-            }
-            Iterator<SAMLAttribute*> i=entry->getAttributes(targeturl.c_str(),pSite);
-           
-            while (i.hasNext())
-            {
-                SAMLAttribute* attr=i.next();
-
-                // Are we supposed to export it?
-                map<xstring,string>::const_iterator iname=g_mapAttribNames.find(attr->getName());
-                if (iname!=g_mapAttribNames.end())
-                {
-                    string hname=g_mapAttribNameToHeader[iname->second];
-                    Iterator<string> vals=attr->getSingleByteValues();
-                    if (hname=="REMOTE_USER:" && vals.hasNext())
-                    {
-                        char* principal=const_cast<char*>(vals.next().c_str());
-                        pn->SetHeader(pfc,"remote-user:",principal);
-                        pfc->pFilterContext=pfc->AllocMem(pfc,strlen(principal)+1,0);
-                        if (pfc->pFilterContext)
-                            strcpy(static_cast<char*>(pfc->pFilterContext),principal);
-                    }   
-                    else
-                    {
-                        string header(" ");
-                        while (vals.hasNext())
-                            header+=vals.next() + " ";
-                        pn->SetHeader(pfc,const_cast<char*>(hname.c_str()),const_cast<char*>(header.c_str()));
-                    }
-                }
-            }
-
-            pSite->g_AuthCache.unlock();  // ---> Release cache lock
-            bLocked=false;
-            return SF_STATUS_REQ_NEXT_NOTIFICATION;
+class ShibTargetIsapiE : public AbstractSPRequest
+{
+  LPEXTENSION_CONTROL_BLOCK m_lpECB;
+  multimap<string,string> m_headers;
+  mutable vector<string> m_certs;
+  mutable string m_body;
+  mutable bool m_gotBody;
+  int m_port;
+  string m_scheme,m_hostname,m_uri;
+  mutable string m_remote_addr,m_remote_user;
+  
+public:
+  ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site)
+      : AbstractSPRequest(SHIBSP_LOGCAT".ISAPI"), m_lpECB(lpECB), m_gotBody(false) {
+    dynabuf ssl(5);
+    GetServerVariable(lpECB,"HTTPS",ssl,5);
+    bool SSL=(ssl=="on" || ssl=="ON");
+
+    // Scheme may come from site def or be derived from IIS.
+    m_scheme=site.m_scheme;
+    if (m_scheme.empty() || !g_bNormalizeRequest)
+        m_scheme = SSL ? "https" : "http";
+
+    // URL path always come from IIS.
+    dynabuf url(256);
+    GetServerVariable(lpECB,"URL",url,255);
+
+    // Port may come from IIS or from site def.
+    dynabuf port(11);
+    if (!g_bNormalizeRequest || (SSL && site.m_sslport.empty()) || (!SSL && site.m_port.empty()))
+        GetServerVariable(lpECB,"SERVER_PORT",port,10);
+    else if (SSL) {
+        strncpy(port,site.m_sslport.c_str(),10);
+        static_cast<char*>(port)[10]=0;
+    }
+    else {
+        strncpy(port,site.m_port.c_str(),10);
+        static_cast<char*>(port)[10]=0;
+    }
+    m_port = atoi(port);
+
+    dynabuf var(32);
+    GetServerVariable(lpECB, "SERVER_NAME", var, 32);
+
+    // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
+    m_hostname=var;
+    if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+        m_hostname=site.m_name;
+
+    /*
+     * IIS screws us over on PATH_INFO (the hits keep on coming). We need to figure out if
+     * the server is set up for proper PATH_INFO handling, or "IIS sucks rabid weasels mode",
+     * which is the default. No perfect way to tell, but we can take a good guess by checking
+     * whether the URL is a substring of the PATH_INFO:
+     * 
+     * e.g. for /Shibboleth.sso/SAML/POST
+     * 
+     *  Bad mode (default):
+     *      URL:        /Shibboleth.sso
+     *      PathInfo:   /Shibboleth.sso/SAML/POST
+     * 
+     *  Good mode:
+     *      URL:        /Shibboleth.sso
+     *      PathInfo:   /SAML/POST
+     */
+    
+    string uri;
+
+    // Clearly we're only in bad mode if path info exists at all.
+    if (lpECB->lpszPathInfo && *(lpECB->lpszPathInfo)) {
+        if (strstr(lpECB->lpszPathInfo,url))
+            // Pretty good chance we're in bad mode, unless the PathInfo repeats the path itself.
+            uri = lpECB->lpszPathInfo;
+        else {
+            uri = url;
+            uri += lpECB->lpszPathInfo;
         }
-        catch (SAMLException& e)
-        {
-            Iterator<saml::QName> i=e.getCodes();
-            int c=0;
-            while (i.hasNext())
-            {
-                   c++;
-                   saml::QName q=i.next();
-                   if (c==1 && !XMLString::compareString(q.getNamespaceURI(),saml::XML::SAMLP_NS) &&
-                    !XMLString::compareString(q.getLocalName(),L(Requester)))
-                    continue;
-                else if (c==2 && !XMLString::compareString(q.getNamespaceURI(),shibboleth::XML::SHIB_NS) &&
-                         !XMLString::compareString(q.getLocalName(),shibboleth::XML::Literals::InvalidHandle))
-                {
-                    if (!bLocked)
-                        pSite->g_AuthCache.lock();  // ---> Grab cache lock
-                    pSite->g_AuthCache.remove(session_id);
-                    pSite->g_AuthCache.unlock();  // ---> Release cache lock
-                    delete entry;
-
-                    log.info("invaliding session due to shib:InvalidHandle code from AA");
-
-                    // Redirect to WAYF.
-                    string wayf("Location: ");
-                    wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
-                                                  "&target=" + url_encode(targeturl.c_str()) + "\r\n";
-                    wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\r\n";
-
-                    // Insert the headers.
-                    pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
-                    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
-                    return SF_STATUS_REQ_FINISHED;
-                }
-                break;
+    }
+    else {
+        uri = url;
+    }
+    
+    // For consistency with Apache, let's add the query string.
+    if (lpECB->lpszQueryString && *(lpECB->lpszQueryString)) {
+        uri += '?';
+        uri += lpECB->lpszQueryString;
+    }
+
+    setRequestURI(uri.c_str());
+  }
+  ~ShibTargetIsapiE() { }
+
+  const char* getScheme() const {
+    return m_scheme.c_str();
+  }
+  const char* getHostname() const {
+    return m_hostname.c_str();
+  }
+  int getPort() const {
+    return m_port;
+  }
+  const char* getMethod() const {
+    return m_lpECB->lpszMethod;
+  }
+  string getContentType() const {
+    return m_lpECB->lpszContentType ? m_lpECB->lpszContentType : "";
+  }
+  long getContentLength() const {
+      return m_lpECB->cbTotalBytes;
+  }
+  string getRemoteUser() const {
+    if (m_remote_user.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_lpECB, "REMOTE_USER", var, 32, false);
+        if (!var.empty())
+            m_remote_user = var;
+    }
+    return m_remote_user;
+  }
+  string getRemoteAddr() const {
+    if (m_remote_addr.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_lpECB, "REMOTE_ADDR", var, 16, false);
+        if (!var.empty())
+            m_remote_addr = var;
+    }
+    return m_remote_addr;
+  }
+  void log(SPLogLevel level, const string& msg) const {
+      AbstractSPRequest::log(level,msg);
+      if (level >= SPError)
+          LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
+  }
+  string getHeader(const char* name) const {
+    string hdr("HTTP_");
+    for (; *name; ++name) {
+        if (*name=='-')
+            hdr += '_';
+        else
+            hdr += toupper(*name);
+    }
+    dynabuf buf(128);
+    GetServerVariable(m_lpECB, const_cast<char*>(hdr.c_str()), buf, 128, false);
+    return buf.empty() ? "" : buf;
+  }
+  void setResponseHeader(const char* name, const char* value) {
+    // Set for later.
+    if (value)
+        m_headers.insert(make_pair(name,value));
+    else
+        m_headers.erase(name);
+  }
+  const char* getQueryString() const {
+    return m_lpECB->lpszQueryString;
+  }
+  const char* getRequestBody() const {
+    if (m_gotBody)
+        return m_body.c_str();
+    if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB?
+        throw opensaml::SecurityPolicyException("Size of request body exceeded 1M size limit.");
+    else if (m_lpECB->cbTotalBytes > m_lpECB->cbAvailable) {
+      m_gotBody=true;
+      char buf[8192];
+      DWORD datalen=m_lpECB->cbTotalBytes;
+      while (datalen) {
+        DWORD buflen=8192;
+        BOOL ret = m_lpECB->ReadClient(m_lpECB->ConnID, buf, &buflen);
+        if (!ret || !buflen)
+            throw IOException("Error reading request body from browser.");
+        m_body.append(buf, buflen);
+        datalen-=buflen;
+      }
+    }
+    else if (m_lpECB->cbAvailable) {
+        m_gotBody=true;
+        m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
+    }
+    return m_body.c_str();
+  }
+  long sendResponse(istream& in, long status) {
+    string hdr = string("Connection: close\r\n");
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+        hdr += i->first + ": " + i->second + "\r\n";
+    hdr += "\r\n";
+    const char* codestr="200 OK";
+    switch (status) {
+        case XMLTOOLING_HTTP_STATUS_UNAUTHORIZED:   codestr="401 Authorization Required"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:      codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND:       codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:          codestr="500 Server Error"; break;
+    }
+    m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, (void*)codestr, 0, (LPDWORD)hdr.c_str());
+    char buf[1024];
+    while (in) {
+        in.read(buf,1024);
+        DWORD resplen = in.gcount();
+        m_lpECB->WriteClient(m_lpECB->ConnID, buf, &resplen, HSE_IO_SYNC);
+    }
+    return HSE_STATUS_SUCCESS;
+  }
+  long sendRedirect(const char* url) {
+    string hdr=string("Location: ") + url + "\r\n"
+      "Content-Type: text/html\r\n"
+      "Content-Length: 40\r\n"
+      "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
+      "Cache-Control: private,no-store,no-cache\r\n";
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+        hdr += i->first + ": " + i->second + "\r\n";
+    hdr += "\r\n";
+    m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, "302 Moved", 0, (LPDWORD)hdr.c_str());
+    static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+    DWORD resplen=40;
+    m_lpECB->WriteClient(m_lpECB->ConnID, (LPVOID)redmsg, &resplen, HSE_IO_SYNC);
+    return HSE_STATUS_SUCCESS;
+  }
+  // Decline happens in the POST processor if this isn't the shire url
+  // Note that it can also happen with HTAccess, but we don't support that, yet.
+  long returnDecline() {
+    return WriteClientError(
+        m_lpECB,
+        "ISAPI extension can only be invoked to process Shibboleth protocol requests."
+               "Make sure the mapped file extension doesn't match actual content."
+        );
+  }
+  long returnOK() {
+      return HSE_STATUS_SUCCESS;
+  }
+
+  const vector<string>& getClientCertificates() const {
+      if (m_certs.empty()) {
+        char CertificateBuf[8192];
+        CERT_CONTEXT_EX ccex;
+        ccex.cbAllocated = sizeof(CertificateBuf);
+        ccex.CertContext.pbCertEncoded = (BYTE*)CertificateBuf;
+        DWORD dwSize = sizeof(ccex);
+
+        if (m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_GET_CERT_INFO_EX, (LPVOID)&ccex, (LPDWORD)dwSize, NULL)) {
+            if (ccex.CertContext.cbCertEncoded) {
+                unsigned int outlen;
+                XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(CertificateBuf), ccex.CertContext.cbCertEncoded, &outlen);
+                m_certs.push_back(reinterpret_cast<char*>(serialized));
+                XMLString::release(&serialized);
             }
-            if (bLocked)
-                pSite->g_AuthCache.unlock();
-               return shib_shar_error(pfc,e);
-        }
-        catch (XMLException& e)
-        {
-            if (bLocked)
-                pSite->g_AuthCache.unlock();
-            auto_ptr<char> msg(XMLString::transcode(e.getMessage()));
-            SAMLException ex(SAMLException::RESPONDER,msg.get());
-            return shib_shar_error(pfc,ex);
         }
+      }
+      return m_certs;
+  }
+
+  // Not used in the extension.
+  void clearHeader(const char* rawname, const char* cginame) { throw runtime_error("clearHeader not implemented"); }
+  void setHeader(const char* name, const char* value) { throw runtime_error("setHeader not implemented"); }
+  void setRemoteUser(const char* user) { throw runtime_error("setRemoteUser not implemented"); }
+};
+
+extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
+{
+    try {
+        ostringstream threadid;
+        threadid << "[" << getpid() << "] isapi_shib_extension" << '\0';
+        xmltooling::NDC ndc(threadid.str().c_str());
+
+        // Determine web site number. This can't really fail, I don't think.
+        dynabuf buf(128);
+        GetServerVariable(lpECB,"INSTANCE_ID",buf,10);
+
+        // Match site instance to host name, skip if no match.
+        map<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
+        if (map_i==g_Sites.end())
+            return WriteClientError(lpECB, "Shibboleth Extension not configured for web site (check <ISAPI> mappings in configuration).");
+
+        ShibTargetIsapiE ste(lpECB, map_i->second);
+        pair<bool,long> res = ste.getServiceProvider().doHandler(ste);
+        if (res.first) return res.second;
+        
+        return WriteClientError(lpECB, "Shibboleth Extension failed to process request");
+
     }
-    catch(bad_alloc)
-    {
-        xmsg="Out of memory.";
-        log.error("out of memory");
+    catch(bad_alloc) {
+        return WriteClientError(lpECB,"Out of Memory");
     }
-    catch(DWORD e)
-    {
+    catch(long e) {
         if (e==ERROR_NO_DATA)
-            xmsg="A required variable or header was empty.";
+            return WriteClientError(lpECB,"A required variable or header was empty.");
         else
-            xmsg="Server detected unexpected IIS error.";
+            return WriteClientError(lpECB,"Server detected unexpected IIS error.");
     }
-    catch(...)
-    {
-        xmsg="Server caught an unknown exception.";
+    catch (exception& e) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+        return WriteClientError(lpECB,"Shibboleth Extension caught an exception, check Event Log for details.");
+    }
+    catch(...) {
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Shibboleth Extension threw an unknown exception.");
+        if (g_catchAll)
+            return WriteClientError(lpECB,"Shibboleth Extension threw an unknown exception.");
+        throw;
     }
 
-    // If we drop here, the exception handler set the proper message.
-    if (bLocked)
-        pSite->g_AuthCache.unlock();
-    return WriteClientError(pfc,xmsg);
+    // If we get here we've got an error.
+    return HSE_STATUS_ERROR;
 }