Changed name of config section.
[shibboleth/sp.git] / isapi_shib / isapi_shib.cpp
index aa71710..1c97f51 100644 (file)
@@ -53,6 +53,8 @@
    8/23/02
 */
 
+#include "config_win32.h"
+
 // SAML Runtime
 #include <saml/saml.h>
 #include <shib/shib.h>
 #include <httpfilt.h>
 #include <httpext.h>
 
-#include <cgiparse.h>
-
 using namespace std;
 using namespace log4cpp;
 using namespace saml;
 using namespace shibboleth;
 using namespace shibtarget;
 
-struct settings_t
-{
-    settings_t() {}
-    settings_t(string& name) : m_name(name) {}
-    
-    string m_name;
-    vector<string> m_mustContain;
-};
-
 // globals
 namespace {
+    static const XMLCh name[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chNull };
+    static const XMLCh port[] = { chLatin_p, chLatin_o, chLatin_r, chLatin_t, chNull };
+    static const XMLCh scheme[] = { chLatin_s, chLatin_c, chLatin_h, chLatin_e, chLatin_m, chLatin_e, chNull };
+    static const XMLCh id[] = { chLatin_i, chLatin_d, chNull };
+    static const XMLCh Implementation[] =
+    { chLatin_I, chLatin_m, chLatin_p, chLatin_l, chLatin_e, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull };
+    static const XMLCh ISAPI[] = { chLatin_I, chLatin_S, chLatin_A, chLatin_P, chLatin_I, chNull };
+    static const XMLCh normalizeRequest[] =
+    { chLatin_n, chLatin_o, chLatin_r, chLatin_m, chLatin_a, chLatin_l, chLatin_i, chLatin_z, chLatin_e,
+      chLatin_R, chLatin_e, chLatin_q, chLatin_u, chLatin_e, chLatin_s, chLatin_t, chNull
+    };
+    static const XMLCh Site[] = { chLatin_S, chLatin_i, chLatin_t, chLatin_e, chNull };
+
+    struct site_t {
+        site_t(const DOMElement* e)
+        {
+            auto_ptr_char n(e->getAttributeNS(NULL,name));
+            auto_ptr_char s(e->getAttributeNS(NULL,scheme));
+            auto_ptr_char p(e->getAttributeNS(NULL,port));
+            if (n.get()) m_name=n.get();
+            if (s.get()) m_scheme=s.get();
+            if (p.get()) m_port=p.get();
+        }
+        string m_scheme,m_name,m_port;
+    };
+    
     HINSTANCE g_hinstDLL;
-    ThreadKey* rpc_handle_key = NULL;
     ShibTargetConfig* g_Config = NULL;
-    vector<settings_t> g_Sites;
-}
-
-void destroy_handle(void* data)
-{
-    delete (RPCHandle*)data;
+    map<string,site_t> g_Sites;
+    bool g_bNormalizeRequest = true;
 }
 
 BOOL LogEvent(
@@ -137,82 +149,75 @@ extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
     return TRUE;
 }
 
+extern "C" BOOL WINAPI TerminateExtension(DWORD)
+{
+    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;
+    }
 
+#ifndef _DEBUG
     try
     {
-        ShibTargetConfig::preinit();
-        g_Config = &(ShibTargetConfig::init(SHIBTARGET_SHIRE, getenv("SHIBCONFIG")));
-        ShibINI& ini = g_Config->getINI();
-
-        // Create the RPC Handle TLS key.
-        rpc_handle_key=ThreadKey::create(destroy_handle);
-
-        Category& log=Category::getInstance("isapi_shib.GetFilterVersion");
-
-        // Read site-specific settings for each instance ID we can find.
-        unsigned short i=1;
-        char iid[8];
-        sprintf(iid,"%u",i++);
-        string hostname;
-        while (ini.get_tag("isapi",iid,false,&hostname))
-        {
-            log.info("configuring for site ID (%d), hostname (%s)",i-1,hostname.empty() ? "null" : hostname.c_str());
-
-            // If no section exists for the host, mark it as a "skip" site.
-            if (!ini.exists(hostname))
-            {
-                log.info("skipping site ID (%d)",i-1);
-                g_Sites.push_back(settings_t());
-                sprintf(iid,"%u",i++);
-                continue;
-            }
-            
-            settings_t settings(hostname);
-            
-            // Content matching string.
-            string mustcontain;
-            if (ini.get_tag(hostname,"mustContain",true,&mustcontain) && !mustcontain.empty())
-            {
-                char* buf=strdup(mustcontain.c_str());
-                _strupr(buf);
-                char* start=buf;
-                while (char* sep=strchr(start,';'))
-                {
-                    *sep='\0';
-                    if (*start)
-                        settings.m_mustContain.push_back(start);
-                    start=sep+1;
+#endif
+        LPCSTR schemadir=getenv("SHIBSCHEMAS");
+        if (!schemadir)
+            schemadir=SHIB_SCHEMAS;
+        LPCSTR config=getenv("SHIBCONFIG");
+        if (!config)
+            config=SHIB_CONFIG;
+        g_Config=&ShibTargetConfig::getConfig();
+        g_Config->setFeatures(
+            ShibTargetConfig::Listener |
+            ShibTargetConfig::Metadata |
+            ShibTargetConfig::AAP |
+            ShibTargetConfig::RequestMapper |
+            ShibTargetConfig::LocalExtensions |
+            ShibTargetConfig::Logging
+            );
+        if (!g_Config->init(schemadir,config)) {
+            g_Config=NULL;
+            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                    "Filter startup failed during initialization, check shire log for help.");
+            return FALSE;
+        }
+        
+        // Access the implementation-specifics for site mappings.
+        IConfig* conf=g_Config->getINI();
+        Locker locker(conf);
+        const IPropertySet* props=conf->getPropertySet("Local");
+        if (props) {
+            const DOMElement* impl=saml::XML::getFirstChildElement(
+                props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
+                );
+            if (impl && (impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,ISAPI))) {
+                const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest);
+                g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t);
+                impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,Site);
+                while (impl) {
+                    auto_ptr_char id(impl->getAttributeNS(NULL,id));
+                    if (id.get())
+                        g_Sites.insert(pair<string,site_t>(id.get(),site_t(impl)));
+                    impl=saml::XML::getNextSiblingElement(impl,ShibTargetConfig::SHIBTARGET_NS,Site);
                 }
-                if (*start)
-                    settings.m_mustContain.push_back(start);
-                free(buf);
             }
-            
-            g_Sites.push_back(settings);
-            sprintf(iid,"%u",i++);
-            hostname.erase();
         }
-    }
-    catch (SAMLException&)
-    {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
-                "Filter startup failed with SAML exception, check shire log for help.");
-        return FALSE;
-    }
-    catch (runtime_error& e)
-    {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
-        return FALSE;
+#ifndef _DEBUG
     }
     catch (...)
     {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with unexpected exception.");
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with an exception.");
         return FALSE;
     }
+#endif
 
     pVer->dwFilterVersion=HTTP_FILTER_REVISION;
     strncpy(pVer->lpszFilterDesc,"Shibboleth ISAPI Filter",SF_MAX_FILTER_DESC_LEN);
@@ -225,14 +230,8 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
     return TRUE;
 }
 
-extern "C" BOOL WINAPI TerminateExtension(DWORD)
-{
-    return TRUE;    // cleanup should happen when filter unloads
-}
-
 extern "C" BOOL WINAPI TerminateFilter(DWORD)
 {
-    delete rpc_handle_key;
     if (g_Config)
         g_Config->shutdown();
     g_Config = NULL;
@@ -260,7 +259,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); }
@@ -293,8 +292,8 @@ bool dynabuf::operator==(const char* s) const
 void GetServerVariable(PHTTP_FILTER_CONTEXT pfc, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
     throw (bad_alloc, DWORD)
 {
-    s.erase();
     s.reserve(size);
+    s.erase();
     size=s.size();
 
     while (!pfc->GetServerVariable(pfc,lpszVariable,s,&size))
@@ -313,8 +312,8 @@ void GetServerVariable(PHTTP_FILTER_CONTEXT pfc, LPSTR lpszVariable, dynabuf& s,
 void GetServerVariable(LPEXTENSION_CONTROL_BLOCK lpECB, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
     throw (bad_alloc, DWORD)
 {
-    s.erase();
     s.reserve(size);
+    s.erase();
     size=s.size();
 
     while (lpECB->GetServerVariable(lpECB->ConnID,lpszVariable,s,&size))
@@ -334,8 +333,8 @@ 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)
 {
-    s.erase();
     s.reserve(size);
+    s.erase();
     size=s.size();
 
     while (!pn->GetHeader(pfc,lpszName,s,&size))
@@ -351,81 +350,130 @@ void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
         throw ERROR_NO_DATA;
 }
 
-inline char hexchar(unsigned short s)
-{
-    return (s<=9) ? ('0' + s) : ('A' + s - 10);
-}
+/****************************************************************************/
+// ISAPI Filter
 
-string url_encode(const char* url) throw (bad_alloc)
+class ShibTargetIsapiF : public ShibTarget
 {
-    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);
-        else
-            s+=*pch;
-    }
-    return s;
-}
-
-string get_target(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, settings_t& site)
-{
-    // 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://";
-
-    // We use the "normalizeRequest" tag to decide how to obtain the server's name.
-    dynabuf buf(256);
-    string tag;
-    if (g_Config->getINI().get_tag(site.m_name,"normalizeRequest",true,&tag) && ShibINI::boolean(tag))
-    {
-        s+=site.m_name;
+public:
+  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn,
+                  const site_t& site) {
+
+    // URL path always come from IIS.
+    dynabuf url(256);
+    GetHeader(pn,pfc,"url",url,256,false);
+
+    // Port may come from IIS or from site def.
+    dynabuf port(11);
+    if (site.m_port.empty() || !g_bNormalizeRequest)
+        GetServerVariable(pfc,"SERVER_PORT",port,10);
+    else {
+        strncpy(port,site.m_port.c_str(),10);
+        static_cast<char*>(port)[10]=0;
     }
-    else
-    {
-        GetServerVariable(pfc,"SERVER_NAME",buf);
-        s+=buf;
+    
+    // Scheme may come from site def or be derived from IIS.
+    const char* scheme=site.m_scheme.c_str();
+    if (!scheme || !*scheme || !g_bNormalizeRequest)
+        scheme=pfc->fIsSecurePort ? "https" : "http";
+
+    // Get the remote address
+    dynabuf remote_addr(16);
+    GetServerVariable(pfc,"REMOTE_ADDR",remote_addr,16);
+
+    // XXX: How do I get the content type and HTTP Method from this context?
+
+    // TODO: Need to allow for use of SERVER_NAME
+
+    init(g_Config, string(scheme), site.m_name, atoi(port),
+        string(url), string(""), // XXX: content type
+        string(remote_addr), string("") // XXX: http method
+        ); 
+
+    m_pfc = pfc;
+    m_pn = pn;
+  }
+  ~ShibTargetIsapiF() { }
+
+  virtual void log(ShibLogLevel level, const string &msg) {
+      LogEvent(NULL, (level == LogLevelDebug ? EVENTLOG_INFORMATION_TYPE :
+                      (level == LogLevelInfo ? EVENTLOG_INFORMATION_TYPE :
+                      (level == LogLevelWarn ? EVENTLOG_WARNING_TYPE : EVENTLOG_ERROR_TYPE))),
+            2100, NULL, msg.c_str());
+  }
+  virtual string getCookies(void) {
+    dynabuf buf(128);
+    GetHeader(m_pn, m_pfc, "Cookie:", buf, 128, false);
+    return buf.empty() ? "" : buf;
+  }
+  
+  virtual void clearHeader(const string &name) {
+    string hdr = name + ":";
+    m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), "");
+  }
+  virtual void setHeader(const string &name, const string &value) {
+    string hdr = name + ":";
+    m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()),
+                   const_cast<char*>(value.c_str()));
+  }
+  virtual string getHeader(const string &name) {
+    string hdr = name + ":";
+    dynabuf buf(1024);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 1024, false);
+    return string(buf);
+  }
+  virtual void setRemoteUser(const string &user) {
+    setHeader(string("remote-user"), user);
+  }
+  virtual string getRemoteUser(void) {
+    return getHeader(string("remote-user"));
+  }
+  virtual void* sendPage(const string &msg, const string content_type,
+      const Iterator<header_t>& headers=EMPTY(header_t), int code=200) {
+    string hdr = string ("Connection: close\r\nContent-type: ") + content_type + "\r\n";
+    while (headers.hasNext()) {
+        const header_t& h=headers.next();
+        hdr += h.first + ": " + h.second + "\r\n";
     }
-
-    GetServerVariable(pfc,"SERVER_PORT",buf,10);
-    if (buf!=(pfc->fIsSecurePort ? "443" : "80"))
-        s=s + ':' + static_cast<char*>(buf);
-
-    GetHeader(pn,pfc,"url",buf,256,false);
-    s+=buf;
-
-    return s;
-}
-
-string get_shire_location(settings_t& site, const char* target)
-{
-    string shireURL;
-    if (g_Config->getINI().get_tag(site.m_name,"shireURL",true,&shireURL) && !shireURL.empty())
-    {
-        if (shireURL[0]!='/')
-            return shireURL;
-        const char* colon=strchr(target,':');
-        const char* slash=strchr(colon+3,'/');
-        string s(target,slash-target);
-        s+=shireURL;
-        return s;
-    }
-    return shireURL;
-}
+    hdr += "\r\n";
+    // XXX Need to handle "code"
+    m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, "200 OK", (DWORD)hdr.c_str(), 0);
+    DWORD resplen = msg.size();
+    m_pfc->WriteClient(m_pfc, (LPVOID)msg.c_str(), &resplen, 0);
+    return (void*)SF_STATUS_REQ_FINISHED;
+  }
+  virtual void* sendRedirect(const string url) {
+    // XXX: Don't support the httpRedirect option, yet.
+    string hdrs=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\r\n";
+    m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER,
+                                "302 Please Wait", (DWORD)hdrs.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 reinterpret_cast<void*>(SF_STATUS_REQ_FINISHED);
+  }
+  // XXX: We might not ever hit the 'decline' status in this filter.
+  //virtual void* returnDecline(void) { }
+  virtual void* returnOK(void) { return (void*) SF_STATUS_REQ_NEXT_NOTIFICATION; }
+
+  // The filter never processes the POST, so stub these methods.
+  virtual void setCookie(const string &name, const string &value) { throw runtime_error("setCookie not implemented"); }
+  virtual string getArgs(void) { throw runtime_error("getArgs not implemented"); }
+  virtual string getPostData(void) { throw runtime_error("getPostData not implemented"); }
+  
+  PHTTP_FILTER_CONTEXT m_pfc;
+  PHTTP_FILTER_PREPROC_HEADERS m_pn;
+};
 
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
 {
     LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
-    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
+    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);
@@ -438,19 +486,6 @@ DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
     return SF_STATUS_REQ_FINISHED;
 }
 
-DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* filename, ShibMLP& mlp)
-{
-    ifstream infile(filename);
-    if (!infile)
-        return WriteClientError(pfc,"Unable to open error template, check settings.");   
-
-    string res = mlp.run(infile);
-    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
-    DWORD resplen=res.length();
-    pfc->WriteClient(pfc,(LPVOID)res.c_str(),&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?
@@ -466,222 +501,375 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
     {
         // 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.
-        if (site_id>g_Sites.size() || g_Sites[site_id-1].m_name.length()==0)
+        // 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;
-        settings_t& site=g_Sites[site_id-1];
+            
+        ostringstream threadid;
+        threadid << "[" << getpid() << "] isapi_shib" << '\0';
+        saml::NDC ndc(threadid.str().c_str());
 
-        string target_url=get_target(pfc,pn,site);
-        string shire_url=get_shire_location(site,target_url.c_str());
+       ShibTargetIsapiF stf(pfc, pn, map_i->second);
 
-        // If the user is accessing the SHIRE acceptance point, pass it on.
-        if (target_url.find(shire_url)!=string::npos)
-            return SF_STATUS_REQ_NEXT_NOTIFICATION;
+       // "false" because we don't override the Shib settings
+       pair<bool,void*> res = stf.doCheckAuthN();
+       if (res.first) return (DWORD)res.second;
 
-        // Get the url request and scan for the must-contain string.
-        if (!site.m_mustContain.empty())
-        {
-            char* upcased=new char[target_url.length()+1];
-            strcpy(upcased,target_url.c_str());
-            _strupr(upcased);
-            for (vector<string>::const_iterator index=site.m_mustContain.begin(); index!=site.m_mustContain.end(); index++)
-                if (strstr(upcased,index->c_str()))
-                    break;
-            delete[] upcased;
-            if (index==site.m_mustContain.end())
-                return SF_STATUS_REQ_NEXT_NOTIFICATION;
+       // "false" because we don't override the Shib settings
+       res = stf.doExportAssertions();
+       if (res.first) return (DWORD)res.second;
+
+       res = stf.doCheckAuthZ();
+       if (res.first) return (DWORD)res.second;
+
+        return SF_STATUS_REQ_NEXT_NOTIFICATION;
+    }
+    catch(bad_alloc) {
+        return WriteClientError(pfc,"Out of Memory");
+    }
+    catch(DWORD e) {
+        if (e==ERROR_NO_DATA)
+            return WriteClientError(pfc,"A required variable or header was empty.");
+        else
+            return WriteClientError(pfc,"Server detected unexpected IIS error.");
+    }
+#ifndef _DEBUG
+    catch(...) {
+        return WriteClientError(pfc,"Server caught an unknown exception.");
+    }
+#endif
+
+    return WriteClientError(pfc,"Server reached unreachable code, save my walrus!");
+}
+        
+
+#if 0
+IRequestMapper::Settings map_request(
+    PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, IRequestMapper* mapper, const site_t& site, string& target
+    )
+{
+    // URL path always come from IIS.
+    dynabuf url(256);
+    GetHeader(pn,pfc,"url",url,256,false);
+
+    // Port may come from IIS or from site def.
+    dynabuf port(11);
+    if (site.m_port.empty() || !g_bNormalizeRequest)
+        GetServerVariable(pfc,"SERVER_PORT",port,10);
+    else {
+        strncpy(port,site.m_port.c_str(),10);
+        static_cast<char*>(port)[10]=0;
+    }
+    
+    // Scheme may come from site def or be derived from IIS.
+    const char* scheme=site.m_scheme.c_str();
+    if (!scheme || !*scheme || !g_bNormalizeRequest)
+        scheme=pfc->fIsSecurePort ? "https" : "http";
+
+    // Start with scheme and hostname.
+    if (g_bNormalizeRequest) {
+        target = string(scheme) + "://" + site.m_name;
+    }
+    else {
+        dynabuf name(64);
+        GetServerVariable(pfc,"SERVER_NAME",name,64);
+        target = string(scheme) + "://" + static_cast<char*>(name);
+    }
+    
+    // If port is non-default, append it.
+    if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443"))
+        target = target + ':' + static_cast<char*>(port);
+
+    // Append path.
+    if (!url.empty())
+        target+=static_cast<char*>(url);
+    
+    return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
+}
+
+DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* page, ShibMLP& mlp)
+{
+    const IPropertySet* props=app->getPropertySet("Errors");
+    if (props) {
+        pair<bool,const char*> p=props->getString(page);
+        if (p.first) {
+            ifstream infile(p.second);
+            if (!infile.fail()) {
+                const char* res = mlp.run(infile,props);
+                if (res) {
+                    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);
+                    DWORD resplen=strlen(res);
+                    pfc->WriteClient(pfc,(LPVOID)res,&resplen,0);
+                    return SF_STATUS_REQ_FINISHED;
+                }
+            }
         }
+    }
 
-        // SSL content check.
-        ShibINI& ini=g_Config->getINI();
-        string tag;
-        if (ini.get_tag(site.m_name,"contentSSLOnly",true,&tag) && ShibINI::boolean(tag) && !pfc->fIsSecurePort)
-        {
-            return WriteClientError(pfc,
-                "This server is configured to deny non-SSL requests for secure resources. "
-                "Try your request again using https instead of http.");
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter unable to open error template.");
+    return WriteClientError(pfc,"Unable to open error template, check settings.");
+}
+
+DWORD WriteRedirectPage(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* file, ShibMLP& mlp, const char* headers=NULL)
+{
+    ifstream infile(file);
+    if (!infile.fail()) {
+        const char* res = mlp.run(infile,app->getPropertySet("Errors"));
+        if (res) {
+            char buf[255];
+            sprintf(buf,"Content-Length: %u\r\nContent-Type: text/html\r\n\r\n",strlen(res));
+            if (headers) {
+                string h(headers);
+                h+=buf;
+                pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)h.c_str(),0);
+            }
+            else
+                pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)buf,0);
+            DWORD resplen=strlen(res);
+            pfc->WriteClient(pfc,(LPVOID)res,&resplen,0);
+            return SF_STATUS_REQ_FINISHED;
         }
+    }
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open redirect template.");
+    return WriteClientError(pfc,"Unable to open redirect template, check settings.");
+}
 
+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);
+        return SF_STATUS_REQ_NEXT_NOTIFICATION;
+    }
+
+    PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification;
+    try
+    {
+        // Determine web site number. This can't really fail, I don't think.
+        dynabuf buf(128);
+        GetServerVariable(pfc,"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 SF_STATUS_REQ_NEXT_NOTIFICATION;
+            
         ostringstream threadid;
-        threadid << "[" << getpid() << "] shire" << '\0';
+        threadid << "[" << getpid() << "] isapi_shib" << '\0';
         saml::NDC ndc(threadid.str().c_str());
+        
+        // We lock the configuration system for the duration.
+        IConfig* conf=g_Config->getINI();
+        Locker locker(conf);
+        
+        // Map request to application and content settings.
+        string targeturl;
+        IRequestMapper* mapper=conf->getRequestMapper();
+        Locker locker2(mapper);
+        IRequestMapper::Settings settings=map_request(pfc,pn,mapper,map_i->second,targeturl);
+        pair<bool,const char*> application_id=settings.first->getString("applicationId");
+        const IApplication* application=conf->getApplication(application_id.second);
+        if (!application)
+            return WriteClientError(pfc,"Unable to map request to application settings, check configuration.");
+        
+        // Declare SHIRE object for this request.
+        SHIRE shire(application);
+        
+        const char* shireURL=shire.getShireURL(targeturl.c_str());
+        if (!shireURL)
+            return WriteClientError(pfc,"Unable to map request to proper shireURL setting, check configuration.");
 
-        // Set SHIRE policies.
-        SHIREConfig config;
-        config.checkIPAddress = (ini.get_tag(site.m_name,"checkIPAddress",true,&tag) && ShibINI::boolean(tag));
-        config.lifetime=config.timeout=0;
-        tag.erase();
-        if (ini.get_tag(site.m_name, "authLifetime", true, &tag))
-            config.lifetime=strtoul(tag.c_str(),NULL,10);
-        tag.erase();
-        if (ini.get_tag(site.m_name, "authTimeout", true, &tag))
-            config.timeout=strtoul(tag.c_str(),NULL,10);
-
-        // Pull the config data we need to handle the various possible conditions.
-        string shib_cookie;
-        if (!ini.get_tag(site.m_name, "cookieName", true, &shib_cookie))
-            return WriteClientError(pfc,"The cookieName configuration setting is missing, check configuration.");
-    
-        string wayfLocation;
-        if (!ini.get_tag(site.m_name, "wayfURL", true, &wayfLocation))
-            return WriteClientError(pfc,"The wayfURL configuration setting is missing, check configuration.");
-    
-        string shireError;
-        if (!ini.get_tag(site.m_name, "shireError", true, &shireError))
-            return WriteClientError(pfc,"The shireError configuration setting is missing, check configuration.");
+        // If the user is accessing the SHIRE acceptance point, pass it on.
+        if (targeturl.find(shireURL)!=string::npos)
+            return SF_STATUS_REQ_NEXT_NOTIFICATION;
 
-        string accessError;
-        if (!ini.get_tag(site.m_name, "accessError", true, &shireError))
-            return WriteClientError(pfc,"The accessError configuration setting is missing, check configuration.");
-        
-        // Get an RPC handle and build the SHIRE object.
-        RPCHandle* rpc_handle = (RPCHandle*)rpc_handle_key->getData();
-        if (!rpc_handle)
-        {
-            rpc_handle = new RPCHandle(shib_target_sockname(), SHIBRPC_PROG, SHIBRPC_VERS_1);
-            rpc_handle_key->setData(rpc_handle);
-        }
-        SHIRE shire(rpc_handle, config, shire_url);
+        // Now check the policy for this request.
+        pair<bool,bool> requireSession=settings.first->getBool("requireSession");
+        pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
+        pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
+        pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
+        if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
+            return WriteClientError(pfc,"HTML-based redirection requires a redirectPage property.");
 
-        // Check for authentication cookie.
+        // Check for session cookie.
         const char* session_id=NULL;
         GetHeader(pn,pfc,"Cookie:",buf,128,false);
-        if (buf.empty() || !(session_id=strstr(buf,shib_cookie.c_str())) || *(session_id+shib_cookie.length())!='=')
-        {
-            // Redirect to WAYF.
-            string wayf("Location: ");
-            wayf+=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target_url.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;
+        Category::getInstance("isapi_shib.HttpFilterProc").debug("cookie header is {%s}",(const char*)buf);
+        if (!buf.empty() && (session_id=strstr(buf,shib_cookie.first))) {
+            session_id+=strlen(shib_cookie.first) + 1;   /* Skip over the '=' */
+            char* cookieend=strchr(session_id,';');
+            if (cookieend)
+                *cookieend = '\0';    /* Ignore anyting after a ; */
+        }
+        
+        if (!session_id || !*session_id) {
+            // If no session required, bail now.
+            if (!requireSession.second)
+                return SF_STATUS_REQ_NEXT_NOTIFICATION;
+    
+            // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
+            const char* areq = shire.getAuthnRequest(targeturl.c_str());
+            if (!httpRedirects.first || httpRedirects.second) {
+                string hdrs=string("Location: ") + areq + "\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\r\n";
+                pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",(DWORD)hdrs.c_str(),0);
+                static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+                DWORD resplen=40;
+                pfc->WriteClient(pfc,(LPVOID)redmsg,&resplen,0);
+                return SF_STATUS_REQ_FINISHED;
+            }
+            else {
+                ShibMLP markupProcessor;
+                markupProcessor.insert("requestURL",areq);
+                return WriteRedirectPage(pfc, application, redirectPage.second, markupProcessor);
+            }
         }
 
-        session_id+=shib_cookie.length() + 1;  /* Skip over the '=' */
-        char* cookieend=strchr(session_id,';');
-        if (cookieend)
-            *cookieend = '\0'; /* Ignore anyting after a ; */
-  
         // Make sure this session is still valid.
         RPCError* status = NULL;
         ShibMLP markupProcessor;
-        bool has_tag = ini.get_tag(site.m_name, "supportContact", true, &tag);
-        markupProcessor.insert("supportContact", has_tag ? tag : "");
-        has_tag = ini.get_tag(site.m_name, "logoLocation", true, &tag);
-        markupProcessor.insert("logoLocation", has_tag ? tag : "");
-        markupProcessor.insert("requestURL", target_url);
+        markupProcessor.insert("requestURL", targeturl);
     
-        GetServerVariable(pfc,"REMOTE_ADDR",buf,16);
+        dynabuf abuf(16);
+        GetServerVariable(pfc,"REMOTE_ADDR",abuf,16);
         try {
-            status = shire.sessionIsValid(session_id, buf, target_url.c_str());
+            status = shire.sessionIsValid(session_id, abuf);
         }
         catch (ShibTargetException &e) {
-            markupProcessor.insert("errorType", "SHIRE Processing Error");
+            markupProcessor.insert("errorType", "Session Processing Error");
             markupProcessor.insert("errorText", e.what());
             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
-            return WriteClientError(pfc, shireError.c_str(), markupProcessor);
+            return WriteClientError(pfc, application, "shire", markupProcessor);
         }
+#ifndef _DEBUG
         catch (...) {
-            markupProcessor.insert("errorType", "SHIRE Processing Error");
+            markupProcessor.insert("errorType", "Session Processing Error");
             markupProcessor.insert("errorText", "Unexpected Exception");
             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
-            return WriteClientError(pfc, shireError.c_str(), markupProcessor);
+            return WriteClientError(pfc, application, "shire", markupProcessor);
         }
-    
+#endif
+
         // Check the status
         if (status->isError()) {
-            if (status->isRetryable()) {
-                // Redirect to WAYF.
+            if (!requireSession.second)
+                return SF_STATUS_REQ_NEXT_NOTIFICATION;
+            else if (status->isRetryable()) {
+                // Oops, session is invalid. Generate AuthnRequest.
                 delete status;
-                string wayf("Location: ");
-                wayf+=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target_url.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;
+                const char* areq = shire.getAuthnRequest(targeturl.c_str());
+                if (!httpRedirects.first || httpRedirects.second) {
+                    string hdrs=string("Location: ") + areq + "\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\r\n";
+                    pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",(DWORD)hdrs.c_str(),0);
+                    static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+                    DWORD resplen=40;
+                    pfc->WriteClient(pfc,(LPVOID)redmsg,&resplen,0);
+                    return SF_STATUS_REQ_FINISHED;
+                }
+                else {
+                    markupProcessor.insert("requestURL",areq);
+                    return WriteRedirectPage(pfc, application, redirectPage.second, markupProcessor);
+                }
             }
             else {
                 // return the error page to the user
                 markupProcessor.insert(*status);
                 delete status;
-                return WriteClientError(pfc, shireError.c_str(), markupProcessor);
+                return WriteClientError(pfc, application, "shire", markupProcessor);
             }
         }
         delete status;
     
         // Move to RM phase.
-        RMConfig rm_config;
-        rm_config.checkIPAddress = config.checkIPAddress;
-        RM rm(rpc_handle,rm_config);
-
-        // Get the attributes.
+        RM rm(application);
         vector<SAMLAssertion*> assertions;
         SAMLAuthenticationStatement* sso_statement=NULL;
-        status = rm.getAssertions(session_id, buf, target_url.c_str(), assertions, &sso_statement);
+
+        try {
+            status = rm.getAssertions(session_id, abuf, assertions, &sso_statement);
+        }
+        catch (ShibTargetException &e) {
+            markupProcessor.insert("errorType", "Attribute Processing Error");
+            markupProcessor.insert("errorText", e.what());
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(pfc, application, "rm", markupProcessor);
+        }
+    #ifndef _DEBUG
+        catch (...) {
+            markupProcessor.insert("errorType", "Attribute Processing Error");
+            markupProcessor.insert("errorText", "Unexpected Exception");
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(pfc, application, "rm", markupProcessor);
+        }
+    #endif
     
         if (status->isError()) {
-            string rmError;
-            if (!ini.get_tag(site.m_name, "rmError", true, &shireError))
-                return WriteClientError(pfc,"The rmError configuration setting is missing, check configuration.");
-    
             markupProcessor.insert(*status);
             delete status;
-            return WriteClientError(pfc, rmError.c_str(), markupProcessor);
+            return WriteClientError(pfc, application, "rm", markupProcessor);
         }
         delete status;
 
-        // Only allow a single assertion...
-        if (assertions.size() > 1) {
-            for (int k = 0; k < assertions.size(); k++)
-              delete assertions[k];
-            delete sso_statement;
-            return WriteClientError(pfc, accessError.c_str(), markupProcessor);
+        // Do we have an access control plugin?
+        if (settings.second) {
+            Locker acllock(settings.second);
+            if (!settings.second->authorized(*sso_statement,assertions)) {
+                for (int k = 0; k < assertions.size(); k++)
+                    delete assertions[k];
+                delete sso_statement;
+                return WriteClientError(pfc, application, "access", markupProcessor);
+            }
         }
 
         // Get the AAP providers, which contain the attribute policy info.
-        Iterator<IAAP*> provs=ShibConfig::getConfig().getAAPProviders();
+        Iterator<IAAP*> provs=application->getAAPProviders();
     
         // Clear out the list of mapped attributes
-        while (provs.hasNext())
-        {
+        while (provs.hasNext()) {
             IAAP* aap=provs.next();
             aap->lock();
-            try
-            {
+            try {
                 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
-                while (rules.hasNext())
-                {
+                while (rules.hasNext()) {
                     const char* header=rules.next()->getHeader();
-                    if (header)
-                        pn->SetHeader(pfc,const_cast<char*>(header),"");
+                    if (header) {
+                        string hname=string(header) + ':';
+                        pn->SetHeader(pfc,const_cast<char*>(hname.c_str()),"");
+                    }
                 }
             }
-            catch(...)
-            {
+            catch(...) {
                 aap->unlock();
                 for (int k = 0; k < assertions.size(); k++)
                   delete assertions[k];
                 delete sso_statement;
-                throw;
+                markupProcessor.insert("errorType", "Attribute Processing Error");
+                markupProcessor.insert("errorText", "Unexpected Exception");
+                markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+                return WriteClientError(pfc, application, "rm", markupProcessor);
             }
             aap->unlock();
         }
         provs.reset();
 
-        // Clear relevant headers.
+        // Maybe export the first assertion.
         pn->SetHeader(pfc,"remote-user:","");
         pn->SetHeader(pfc,"Shib-Attributes:","");
-        pn->SetHeader(pfc,"Shib-Origin-Site:","");
-        pn->SetHeader(pfc,"Shib-Authentication-Method:","");
-
-        // Maybe export the assertion.
-        if (ini.get_tag(site.m_name,"exportAssertion",true,&tag) && ShibINI::boolean(tag))
-        {
+        pair<bool,bool> exp=settings.first->getBool("exportAssertion");
+        if (exp.first && exp.second && assertions.size()) {
             string assertion;
             RM::serialize(*(assertions[0]), assertion);
             string::size_type lfeed;
@@ -690,52 +878,88 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
             pn->SetHeader(pfc,"Shib-Attributes:",const_cast<char*>(assertion.c_str()));
         }
         
-        if (sso_statement)
-        {
-            auto_ptr<char> os(XMLString::transcode(sso_statement->getSubject()->getNameQualifier()));
-            auto_ptr<char> am(XMLString::transcode(sso_statement->getAuthMethod()));
-            pn->SetHeader(pfc,"Shib-Origin-Site:", os.get());
-            pn->SetHeader(pfc,"Shib-Authentication-Method:", am.get());
+        pn->SetHeader(pfc,"Shib-Origin-Site:","");
+        pn->SetHeader(pfc,"Shib-Authentication-Method:","");
+        pn->SetHeader(pfc,"Shib-NameIdentifier-Format:","");
+
+        // Export the SAML AuthnMethod and the origin site name.
+        auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
+        auto_ptr_char am(sso_statement->getAuthMethod());
+        pn->SetHeader(pfc,"Shib-Origin-Site:", const_cast<char*>(os.get()));
+        pn->SetHeader(pfc,"Shib-Authentication-Method:", const_cast<char*>(am.get()));
+
+        // Export NameID?
+        AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
+        if (!wrapper.fail() && wrapper->getHeader()) {
+            auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
+            auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
+            pn->SetHeader(pfc,"Shib-NameIdentifier-Format:",const_cast<char*>(form.get()));
+            if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
+                char* principal=const_cast<char*>(nameid.get());
+                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 hname=string(wrapper->getHeader()) + ':';
+                pn->SetHeader(pfc,const_cast<char*>(wrapper->getHeader()),const_cast<char*>(nameid.get()));
+            }
         }
 
-        // Export the attributes. Only supports a single statement.
-        Iterator<SAMLAttribute*> j = assertions.size()==1 ? RM::getAttributes(*(assertions[0])) : EMPTY(SAMLAttribute*);
-        while (j.hasNext())
-        {
-            SAMLAttribute* attr=j.next();
-    
-            // Are we supposed to export it?
-            const char* hname=NULL;
-            AAP wrapper(attr->getName(),attr->getNamespace());
-            if (!wrapper.fail())
-                hname=wrapper->getHeader();
-            if (hname)
-            {
-                Iterator<string> vals=attr->getSingleByteValues();
-                if (!strcmp(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;
-                    for (int it = 0; vals.hasNext(); it++) {
-                        string value = vals.next();
-                        for (string::size_type pos = value.find_first_of(";", string::size_type(0)); pos != string::npos; pos = value.find_first_of(";", pos)) {
-                            value.insert(pos, "\\");
-                            pos += 2;
-                        }
-                        if (it == 0)
-                            header=value;
-                        else
-                            header=header + ';' + value;
+        pn->SetHeader(pfc,"Shib-Application-ID:","");
+        pn->SetHeader(pfc,"Shib-Application-ID:",const_cast<char*>(application_id.second));
+
+        // Export the attributes.
+        Iterator<SAMLAssertion*> a_iter(assertions);
+        while (a_iter.hasNext()) {
+            SAMLAssertion* assert=a_iter.next();
+            Iterator<SAMLStatement*> statements=assert->getStatements();
+            while (statements.hasNext()) {
+                SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
+                if (!astate)
+                    continue;
+                Iterator<SAMLAttribute*> attrs=astate->getAttributes();
+                while (attrs.hasNext()) {
+                    SAMLAttribute* attr=attrs.next();
+        
+                    // Are we supposed to export it?
+                    AAP wrapper(provs,attr->getName(),attr->getNamespace());
+                    if (wrapper.fail() || !wrapper->getHeader())
+                        continue;
+                
+                    Iterator<string> vals=attr->getSingleByteValues();
+                    if (!strcmp(wrapper->getHeader(),"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);
                     }
-                    string hname2=string(hname) + ':';
-                    pn->SetHeader(pfc,const_cast<char*>(hname2.c_str()),const_cast<char*>(header.c_str()));
+                    else {
+                        int it=0;
+                        string header;
+                        string hname=string(wrapper->getHeader()) + ':';
+                        GetHeader(pn,pfc,const_cast<char*>(hname.c_str()),buf,256,false);
+                        if (!buf.empty()) {
+                            header=buf;
+                            it++;
+                        }
+                        for (; vals.hasNext(); it++) {
+                            string value = vals.next();
+                            for (string::size_type pos = value.find_first_of(";", string::size_type(0));
+                                    pos != string::npos;
+                                    pos = value.find_first_of(";", pos)) {
+                                value.insert(pos, "\\");
+                                pos += 2;
+                            }
+                            if (it == 0)
+                                header=value;
+                            else
+                                header=header + ';' + value;
+                        }
+                        pn->SetHeader(pfc,const_cast<char*>(hname.c_str()),const_cast<char*>(header.c_str()));
+                       }
                 }
             }
         }
@@ -747,62 +971,33 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
-    catch(bad_alloc)
-    {
+    catch(bad_alloc) {
         return WriteClientError(pfc,"Out of Memory");
     }
-    catch(DWORD e)
-    {
+    catch(DWORD e) {
         if (e==ERROR_NO_DATA)
             return WriteClientError(pfc,"A required variable or header was empty.");
         else
             return WriteClientError(pfc,"Server detected unexpected IIS error.");
     }
-    catch(...)
-    {
+#ifndef _DEBUG
+    catch(...) {
         return WriteClientError(pfc,"Server caught an unknown exception.");
     }
+#endif
 
-    return WriteClientError(pfc,"Server reached unreachable code!");
+    return WriteClientError(pfc,"Server reached unreachable code, save my walrus!");
 }
+#endif // 0
 
-string get_target(LPEXTENSION_CONTROL_BLOCK lpECB, settings_t& site)
-{
-    string s;
-    dynabuf buf(256);
-    GetServerVariable(lpECB,"HTTPS",buf);
-    bool SSL=(buf=="on");
-    if (SSL)
-        s="https://";
-    else
-        s="http://";
-
-    // We use the "normalizeRequest" tag to decide how to obtain the server's name.
-    string tag;
-    if (g_Config->getINI().get_tag(site.m_name,"normalizeRequest",true,&tag) && ShibINI::boolean(tag))
-    {
-        s+=site.m_name;
-    }
-    else
-    {
-        GetServerVariable(lpECB,"SERVER_NAME",buf);
-        s+=buf;
-    }
-
-    GetServerVariable(lpECB,"SERVER_PORT",buf,10);
-    if (buf!=(SSL ? "443" : "80"))
-        s=s + ':' + static_cast<char*>(buf);
-
-    GetServerVariable(lpECB,"URL",buf,255);
-    s+=buf;
-
-    return s;
-}
+/****************************************************************************/
+// ISAPI Extension
 
 DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
 {
     LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
-    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
+    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);
@@ -814,174 +1009,485 @@ DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
     return HSE_STATUS_SUCCESS;
 }
 
-DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* filename, ShibMLP& mlp)
-{
-    ifstream infile(filename);
-    if (!infile)
-        return WriteClientError(lpECB,"Unable to open error template, check settings.");   
-
-    string res = mlp.run(infile);
-    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
-    DWORD resplen=res.length();
-    lpECB->WriteClient(lpECB->ConnID,(LPVOID)res.c_str(),&resplen,0);
-    return HSE_STATUS_SUCCESS;
-}
 
-extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
+class ShibTargetIsapiE : public ShibTarget
 {
-    ostringstream threadid;
-    threadid << "[" << getpid() << "] shire" << '\0';
-    saml::NDC ndc(threadid.str().c_str());
+public:
+  ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site) :
+    m_cookie(NULL)
+  {
+    dynabuf ssl(5);
+    GetServerVariable(lpECB,"HTTPS",ssl,5);
+    bool SSL=(ssl=="on" || ssl=="ON");
+
+    // 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 (site.m_port.empty() || !g_bNormalizeRequest)
+        GetServerVariable(lpECB,"SERVER_PORT",port,10);
+    else {
+        strncpy(port,site.m_port.c_str(),10);
+        static_cast<char*>(port)[10]=0;
+    }
 
-    ShibINI& ini = g_Config->getINI();
-    string shireError;
-    ShibMLP markupProcessor;
+    // Scheme may come from site def or be derived from IIS.
+    const char* scheme=site.m_scheme.c_str();
+    if (!scheme || !*scheme || !g_bNormalizeRequest) {
+        scheme = SSL ? "https" : "http";
+    }
+
+    // Get the remote address
+    dynabuf remote_addr(16);
+    GetServerVariable(lpECB, "REMOTE_ADDR", remote_addr, 16);
+
+    init(g_Config, string(scheme), site.m_name, atoi(port),
+        string(url), string(lpECB->lpszContentType ? lpECB->lpszContentType : ""),
+        string(remote_addr), string(lpECB->lpszMethod)
+        ); 
+
+    m_lpECB = lpECB;
+  }
+  ~ShibTargetIsapiE() { }
+
+  virtual void log(ShibLogLevel level, const string &msg) {
+      LogEvent(NULL, (level == LogLevelDebug ? EVENTLOG_INFORMATION_TYPE :
+                        (level == LogLevelInfo ? EVENTLOG_INFORMATION_TYPE :
+                        (level == LogLevelWarn ? EVENTLOG_WARNING_TYPE : EVENTLOG_ERROR_TYPE))),
+            2100, NULL, msg.c_str());
+  }
+  virtual void setCookie(const string &name, const string &value) {
+    // Set the cookie for later.  Use it during the redirect.
+    m_cookie += "Set-Cookie: " + name + "=" + value + "\r\n";
+  }
+  virtual string getArgs(void) {
+    return string(m_lpECB->lpszQueryString ? m_lpECB->lpszQueryString : "");
+  }
+  virtual string getPostData(void) {
+    if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB?
+      throw ShibTargetException(SHIBRPC_OK,
+                               "blocked too-large a post to SHIRE POST processor");
+    else if (m_lpECB->cbTotalBytes != m_lpECB->cbAvailable) {
+      string cgistr;
+      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 ShibTargetException(SHIBRPC_OK,
+                                   "error reading POST data from browser");
+       cgistr.append(buf, buflen);
+       datalen-=buflen;
+      }
+      return cgistr;
+    }
+    else
+      return string(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
+  }
+  virtual void* sendPage(const string &msg, const string content_type,
+                        const Iterator<header_t>& headers=EMPTY(header_t), int code=200) {
+    string hdr = string ("Connection: close\r\nContent-type: ") + content_type + "\r\n";
+    for (int k = 0; k < headers.size(); k++) {
+      hdr += headers[k].first + ": " + headers[k].second + "\r\n";
+    }
+    hdr += "\r\n";
+    // XXX Need to handle "code"
+    m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER,
+                                  "200 OK", 0, (LPDWORD)hdr.c_str());
+    DWORD resplen = msg.size();
+    m_lpECB->WriteClient(m_lpECB->ConnID, (LPVOID)msg.c_str(), &resplen, HSE_IO_SYNC);
+    return (void*)HSE_STATUS_SUCCESS;
+  }
+  virtual void* sendRedirect(const string url) {
+    // XXX: Don't support the httpRedirect option, yet.
+    string hdrs = m_cookie + "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\r\n";
+    m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER,
+                                "302 Moved", 0, (LPDWORD)hdrs.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 (void*)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 suppor that, yet.
+  virtual void* returnDecline(void) {
+    return (void*)
+      WriteClientError(m_lpECB, "UISAPA extension can only be unvoked to process incoming sessions."
+                      "Make sure the mapped file extension doesn't match actual content.");
+  }
+  virtual void* returnOK(void) { return (void*) HSE_STATUS_SUCCESS; }
+
+  // Not used in the extension.
+  virtual string getCookies(void) { throw runtime_error("getCookies not implemented"); }
+  virtual void clearHeader(const string &name) { throw runtime_error("clearHeader not implemented"); }
+  virtual void setHeader(const string &name, const string &value) { throw runtime_error("setHeader not implemented"); }
+  virtual string getHeader(const string &name) { throw runtime_error("getHeader not implemented"); }
+  virtual void setRemoteUser(const string &user) { throw runtime_error("setRemoteUser not implemented"); }
+  virtual string getRemoteUser(void) { throw runtime_error("getRemoteUser not implemented"); }
+
+  LPEXTENSION_CONTROL_BLOCK m_lpECB;
+  string m_cookie;
+};
 
+extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
+{
+    string targeturl;
+    const IApplication* application=NULL;
     try
     {
+        ostringstream threadid;
+        threadid << "[" << getpid() << "] shire_handler" << '\0';
+        saml::NDC ndc(threadid.str().c_str());
+
         // Determine web site number. This can't really fail, I don't think.
         dynabuf buf(128);
-        ULONG site_id=0;
         GetServerVariable(lpECB,"INSTANCE_ID",buf,10);
-        if ((site_id=strtoul(buf,NULL,10))==0)
-            return WriteClientError(lpECB,"IIS site instance appears to be invalid.");
 
-        // Match site instance to site settings.
-        if (site_id>g_Sites.size() || g_Sites[site_id-1].m_name.length()==0)
-            return WriteClientError(lpECB,"Shibboleth filter not configured for this web site.");
-        settings_t& site=g_Sites[site_id-1];
-
-        if (!ini.get_tag(site.m_name, "shireError", true, &shireError))
-            return WriteClientError(lpECB,"The shireError configuration setting is missing, check configuration.");
-
-        string target_url=get_target(lpECB,site);
-        string shire_url = get_shire_location(site,target_url.c_str());
-
-        // Set SHIRE policies.
-        SHIREConfig config;
-        string tag;
-        config.checkIPAddress = (ini.get_tag(site.m_name,"checkIPAddress",true,&tag) && ShibINI::boolean(tag));
-        config.lifetime=config.timeout=0;
-        tag.erase();
-        if (ini.get_tag(site.m_name, "authLifetime", true, &tag))
-            config.lifetime=strtoul(tag.c_str(),NULL,10);
-        tag.erase();
-        if (ini.get_tag(site.m_name, "authTimeout", true, &tag))
-            config.timeout=strtoul(tag.c_str(),NULL,10);
-
-        // Pull the config data we need to handle the various possible conditions.
-        string shib_cookie;
-        if (!ini.get_tag(site.m_name, "cookieName", true, &shib_cookie))
-            return WriteClientError(lpECB,"The cookieName configuration setting is missing, check configuration.");
+        // 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 this web site.");
+
+       ShibTargetIsapiE ste(lpECB, map_i->second);
+       pair<bool,void*> res = ste.doHandleProfile();
+       if (res.first) return (DWORD)res.second;
+
+       return WriteClientError(lpECB, "Shibboleth Extension failed to process POST");
+
+    } catch (...) {
+      return WriteClientError(lpECB,
+                             "Shibboleth Extension caught an unknown error. "
+                             "Memory Failure?");
+    }
+
+    // If we get here we've got an error.
+    return HSE_STATUS_ERROR;
+}
+
+#if 0
+IRequestMapper::Settings map_request(
+    LPEXTENSION_CONTROL_BLOCK lpECB, IRequestMapper* mapper, const site_t& site, string& target
+    )
+{
+    dynabuf ssl(5);
+    GetServerVariable(lpECB,"HTTPS",ssl,5);
+    bool SSL=(ssl=="on" || ssl=="ON");
+
+    // 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 (site.m_port.empty() || !g_bNormalizeRequest)
+        GetServerVariable(lpECB,"SERVER_PORT",port,10);
+    else {
+        strncpy(port,site.m_port.c_str(),10);
+        static_cast<char*>(port)[10]=0;
+    }
+
+    // Scheme may come from site def or be derived from IIS.
+    const char* scheme=site.m_scheme.c_str();
+    if (!scheme || !*scheme || !g_bNormalizeRequest) {
+        scheme = SSL ? "https" : "http";
+    }
+
+    // Start with scheme and hostname.
+    if (g_bNormalizeRequest) {
+        target = string(scheme) + "://" + site.m_name;
+    }
+    else {
+        dynabuf name(64);
+        GetServerVariable(lpECB,"SERVER_NAME",name,64);
+        target = string(scheme) + "://" + static_cast<char*>(name);
+    }
     
-        string wayfLocation;
-        if (!ini.get_tag(site.m_name, "wayfURL", true, &wayfLocation))
-            return WriteClientError(lpECB,"The wayfURL configuration setting is missing, check configuration.");
+    // If port is non-default, append it.
+    if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443"))
+        target = target + ':' + static_cast<char*>(port);
+
+    // Append path.
+    if (!url.empty())
+        target+=static_cast<char*>(url);
     
-        bool has_tag = ini.get_tag(site.m_name, "supportContact", true, &tag);
-        markupProcessor.insert("supportContact", has_tag ? tag : "");
-        has_tag = ini.get_tag(site.m_name, "logoLocation", true, &tag);
-        markupProcessor.insert("logoLocation", has_tag ? tag : "");
-        markupProcessor.insert("requestURL", target_url.c_str());
-  
-        // Get an RPC handle and build the SHIRE object.
-        RPCHandle* rpc_handle = (RPCHandle*)rpc_handle_key->getData();
-        if (!rpc_handle)
-        {
-            rpc_handle = new RPCHandle(shib_target_sockname(), SHIBRPC_PROG, SHIBRPC_VERS_1);
-            rpc_handle_key->setData(rpc_handle);
+    return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
+}
+
+DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* page, ShibMLP& mlp)
+{
+    const IPropertySet* props=app->getPropertySet("Errors");
+    if (props) {
+        pair<bool,const char*> p=props->getString(page);
+        if (p.first) {
+            ifstream infile(p.second);
+            if (!infile.fail()) {
+                const char* res = mlp.run(infile,props);
+                if (res) {
+                    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);
+                    DWORD resplen=strlen(res);
+                    lpECB->WriteClient(lpECB->ConnID,(LPVOID)res,&resplen,0);
+                    return HSE_STATUS_SUCCESS;
+                }
+            }
         }
-        SHIRE shire(rpc_handle, config, shire_url.c_str());
+    }
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open error template.");
+    return WriteClientError(lpECB,"Unable to open error template, check settings.");
+}
 
-        // Process SHIRE POST
-        if (ini.get_tag(site.m_name, "shireSSLOnly", true, &tag) && ShibINI::boolean(tag))
-        {
-            // Make sure this is SSL, if it should be.
+DWORD WriteRedirectPage(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* file, ShibMLP& mlp, const char* headers=NULL)
+{
+    ifstream infile(file);
+    if (!infile.fail()) {
+        const char* res = mlp.run(infile,app->getPropertySet("Errors"));
+        if (res) {
+            char buf[255];
+            sprintf(buf,"Content-Length: %u\r\nContent-Type: text/html\r\n\r\n",strlen(res));
+            if (headers) {
+                string h(headers);
+                h+=buf;
+                lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)h.c_str());
+            }
+            else
+                lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)buf);
+            DWORD resplen=strlen(res);
+            lpECB->WriteClient(lpECB->ConnID,(LPVOID)res,&resplen,0);
+            return HSE_STATUS_SUCCESS;
+        }
+    }
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open redirect template.");
+    return WriteClientError(lpECB,"Unable to open redirect template, check settings.");
+}
+
+extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
+{
+    string targeturl;
+    const IApplication* application=NULL;
+    try
+    {
+        ostringstream threadid;
+        threadid << "[" << getpid() << "] shire_handler" << '\0';
+        saml::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 filter not configured for this web site.");
+            
+        // We lock the configuration system for the duration.
+        IConfig* conf=g_Config->getINI();
+        Locker locker(conf);
+        
+        // Map request to application and content settings.
+        IRequestMapper* mapper=conf->getRequestMapper();
+        Locker locker2(mapper);
+        IRequestMapper::Settings settings=map_request(lpECB,mapper,map_i->second,targeturl);
+        pair<bool,const char*> application_id=settings.first->getString("applicationId");
+        application=conf->getApplication(application_id.second);
+        const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
+        if (!application || !sessionProps)
+            return WriteClientError(lpECB,"Unable to map request to application session settings, check configuration.");
+
+        SHIRE shire(application);
+        
+        const char* shireURL=shire.getShireURL(targeturl.c_str());
+        if (!shireURL)
+            return WriteClientError(lpECB,"Unable to map request to proper shireURL setting, check configuration.");
+
+        // Make sure we only process the SHIRE requests.
+        if (!strstr(targeturl.c_str(),shireURL))
+            return WriteClientError(lpECB,"ISAPI extension can only be invoked to process incoming sessions."
+                "Make sure the mapped file extension doesn't match actual content.");
+
+        pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
+
+        // Make sure this is SSL, if it should be
+        pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
+        if (!shireSSL.first || shireSSL.second) {
             GetServerVariable(lpECB,"HTTPS",buf,10);
             if (buf!="on")
                 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to SHIRE POST processor");
         }
         
-        // Make sure this is a POST
-        if (stricmp(lpECB->lpszMethod,"POST"))
+        pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
+        pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
+        if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
+            return WriteClientError(lpECB,"HTML-based redirection requires a redirectPage property.");
+        
+        // Check for Mac web browser
+        /*
+        bool bSafari=false;
+        dynabuf agent(64);
+        GetServerVariable(lpECB,"HTTP_USER_AGENT",agent,64);
+        if (strstr(agent,"AppleWebKit/"))
+            bSafari=true;
+        */
+        
+        // If this is a GET, we manufacture an AuthnRequest.
+        if (!stricmp(lpECB->lpszMethod,"GET")) {
+            const char* areq=lpECB->lpszQueryString ? shire.getLazyAuthnRequest(lpECB->lpszQueryString) : NULL;
+            if (!areq)
+                throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
+            if (!httpRedirects.first || httpRedirects.second) {
+                string hdrs=string("Location: ") + areq + "\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\r\n";
+                lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)hdrs.c_str());
+                static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+                DWORD resplen=40;
+                lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC);
+                return HSE_STATUS_SUCCESS;
+            }
+            else {
+                ShibMLP markupProcessor;
+                markupProcessor.insert("requestURL",areq);
+                return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor);
+            }
+        }
+        else if (stricmp(lpECB->lpszMethod,"POST"))
             throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to SHIRE POST processor");
 
         // Sure sure this POST is an appropriate content type
         if (!lpECB->lpszContentType || stricmp(lpECB->lpszContentType,"application/x-www-form-urlencoded"))
             throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to SHIRE POST processor");
     
-        // Make sure the "bytes sent" is a reasonable number and that we have all of it.
+        // Read the data.
+        pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
         if (lpECB->cbTotalBytes > 1024*1024) // 1MB?
-            throw ShibTargetException (SHIBRPC_OK,"blocked too-large a post to SHIRE POST processor");
-        else if (lpECB->cbTotalBytes>lpECB->cbAvailable)
-            throw ShibTargetException (SHIBRPC_OK,"blocked incomplete post to SHIRE POST processor");
-
-        // Parse the incoming data.
-        HQUERY params=ParseQuery(lpECB);
-        if (!params)
-            throw ShibTargetException (SHIBRPC_OK,"unable to parse form data");
-
-        // Make sure the TARGET parameter exists
-        const char* target = QueryValue(params,"TARGET");
-        if (!target || *target == '\0')
-            throw ShibTargetException(SHIBRPC_OK,"SHIRE POST failed to find TARGET parameter");
+            throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to SHIRE POST processor");
+        else if (lpECB->cbTotalBytes!=lpECB->cbAvailable) {
+            string cgistr;
+            char buf[8192];
+            DWORD datalen=lpECB->cbTotalBytes;
+            while (datalen) {
+                DWORD buflen=8192;
+                BOOL ret=lpECB->ReadClient(lpECB->ConnID,buf,&buflen);
+                if (!ret || !buflen)
+                    throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
+                cgistr.append(buf,buflen);
+                datalen-=buflen;
+            }
+            elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
+        }
+        else
+            elements=shire.getFormSubmission(reinterpret_cast<char*>(lpECB->lpbData),lpECB->cbAvailable);
     
-        // Make sure the SAMLResponse parameter exists
-        const char* post = QueryValue(params,"SAMLResponse");
-        if (!post || *post == '\0')
-            throw ShibTargetException (SHIBRPC_OK,"SHIRE POST failed to find SAMLResponse parameter");
-
+        // Make sure the SAML Response parameter exists
+        if (!elements.first || !*elements.first)
+            throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
+    
+        // Make sure the target parameter exists
+        if (!elements.second || !*elements.second)
+            throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
+            
         GetServerVariable(lpECB,"REMOTE_ADDR",buf,16);
 
         // Process the post.
         string cookie;
-        RPCError* status = shire.sessionCreate(post,buf,cookie);
-    
+        RPCError* status=NULL;
+        ShibMLP markupProcessor;
+        markupProcessor.insert("requestURL", targeturl.c_str());
+        try {
+            status = shire.sessionCreate(elements.first,buf,cookie);
+        }
+        catch (ShibTargetException &e) {
+            markupProcessor.insert("errorType", "Session Creation Service Error");
+            markupProcessor.insert("errorText", e.what());
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(lpECB, application, "shire", markupProcessor);
+        }
+#ifndef _DEBUG
+        catch (...) {
+            markupProcessor.insert("errorType", "Session Creation Service Error");
+            markupProcessor.insert("errorText", "Unexpected Exception");
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(lpECB, application, "shire", markupProcessor);
+        }
+#endif
+
         if (status->isError()) {
             if (status->isRetryable()) {
                 delete status;
-                string wayf=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target);
-                DWORD len=wayf.length();
-                if (lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_URL_REDIRECT_RESP,(LPVOID)wayf.c_str(),&len,0))
+                const char* loc=shire.getAuthnRequest(elements.second);
+                if (!httpRedirects.first || httpRedirects.second) {
+                    string hdrs=string("Location: ") + loc + "\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\r\n";
+                    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)hdrs.c_str());
+                    static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+                    DWORD resplen=40;
+                    lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC);
                     return HSE_STATUS_SUCCESS;
-                return HSE_STATUS_ERROR;
+                }
+                else {
+                    markupProcessor.insert("requestURL",loc);
+                    return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor);
+                }
             }
     
             // Return this error to the user.
             markupProcessor.insert(*status);
             delete status;
-            return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
+            return WriteClientError(lpECB,application,"shire",markupProcessor);
         }
         delete status;
     
         // We've got a good session, set the cookie and redirect to target.
-        shib_cookie = "Set-Cookie: " + shib_cookie + '=' + cookie + "; path=/\r\n" 
-            "Location: " + target + "\r\n"
+        cookie = string("Set-Cookie: ") + shib_cookie.first + '=' + cookie + shib_cookie.second + "\r\n"
             "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
-            "Cache-Control: private,no-store,no-cache\r\n"
-            "Connection: close\r\n";
-        HSE_SEND_HEADER_EX_INFO hinfo;
-        hinfo.pszStatus="302 Moved";
-        hinfo.pszHeader=shib_cookie.c_str();
-        hinfo.cchStatus=9;
-        hinfo.cchHeader=shib_cookie.length();
-        hinfo.fKeepConn=FALSE;
-        if (lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER_EX,&hinfo,0,0))
+            "Cache-Control: private,no-store,no-cache\r\n";
+        if (!httpRedirects.first || httpRedirects.second) {
+            cookie=cookie + "Content-Type: text/html\r\nLocation: " + elements.second + "\r\nContent-Length: 40\r\n\r\n";
+            lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)cookie.c_str());
+            static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+            DWORD resplen=40;
+            lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC);
             return HSE_STATUS_SUCCESS;
+        }
+        else {
+            markupProcessor.insert("requestURL",elements.second);
+            return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor, cookie.c_str());
+        }
     }
     catch (ShibTargetException &e) {
-        markupProcessor.insert ("errorType", "SHIRE Processing Error");
-        markupProcessor.insert ("errorText", e.what());
-        markupProcessor.insert ("errorDesc", "An error occurred while processing your request.");
-        return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
+        if (application) {
+            ShibMLP markupProcessor;
+            markupProcessor.insert("requestURL", targeturl.c_str());
+            markupProcessor.insert("errorType", "Session Creation Service Error");
+            markupProcessor.insert("errorText", e.what());
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(lpECB,application,"shire",markupProcessor);
+        }
     }
+#ifndef _DEBUG
     catch (...) {
-        markupProcessor.insert ("errorType", "SHIRE Processing Error");
-        markupProcessor.insert ("errorText", "Unexpected Exception");
-        markupProcessor.insert ("errorDesc", "An error occurred while processing your request.");
-        return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
+        if (application) {
+            ShibMLP markupProcessor;
+            markupProcessor.insert("requestURL", targeturl.c_str());
+            markupProcessor.insert("errorType", "Session Creation Service Error");
+            markupProcessor.insert("errorText", "Unexpected Exception");
+            markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
+            return WriteClientError(lpECB,application,"shire",markupProcessor);
+        }
     }
-    
+#endif
+
     return HSE_STATUS_ERROR;
 }
-
+#endif // 0