Add support for returning 304 responses.
[shibboleth/sp.git] / isapi_shib / isapi_shib.cpp
index 25ed8a7..014f34c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2007 Internet2
+ *  Copyright 2001-2010 Internet2
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
 /**
  * isapi_shib.cpp
  *
- * Shibboleth ISAPI filter
+ * Shibboleth ISAPI filter.
  */
 
 #define SHIBSP_LITE
 
 #define _CRT_NONSTDC_NO_DEPRECATE 1
 #define _CRT_SECURE_NO_DEPRECATE 1
+#define _CRT_RAND_S
 
+#include <shibsp/exceptions.h>
 #include <shibsp/AbstractSPRequest.h>
 #include <shibsp/SPConfig.h>
 #include <shibsp/ServiceProvider.h>
+
+#include <set>
+#include <sstream>
+#include <fstream>
+#include <stdexcept>
+#include <process.h>
 #include <xmltooling/unicode.h>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
 #include <xercesc/util/Base64.hpp>
 #include <xercesc/util/XMLUniDefs.hpp>
 
-#include <set>
-#include <sstream>
-#include <fstream>
-#include <process.h>
-
 #include <windows.h>
 #include <httpfilt.h>
 #include <httpext.h>
@@ -66,10 +69,10 @@ namespace {
     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));
-            auto_ptr_char p2(e->getAttributeNS(NULL,sslport));
+            auto_ptr_char n(e->getAttributeNS(nullptr,name));
+            auto_ptr_char s(e->getAttributeNS(nullptr,scheme));
+            auto_ptr_char p(e->getAttributeNS(nullptr,port));
+            auto_ptr_char p2(e->getAttributeNS(nullptr,sslport));
             if (n.get()) m_name=n.get();
             if (s.get()) m_scheme=s.get();
             if (p.get()) m_port=p.get();
@@ -87,18 +90,14 @@ namespace {
         set<string> m_aliases;
     };
 
-    struct context_t {
-       char* m_user;
-       bool m_checked;
-    };
-
     HINSTANCE g_hinstDLL;
-    SPConfig* g_Config = NULL;
+    SPConfig* g_Config = nullptr;
     map<string,site_t> g_Sites;
     bool g_bNormalizeRequest = true;
-    string g_unsetHeaderValue;
+    string g_unsetHeaderValue,g_spoofKey;
     bool g_checkSpoofing = true;
     bool g_catchAll = false;
+    bool g_bSafeHeaderNames = false;
     vector<string> g_NoCerts;
 }
 
@@ -109,13 +108,24 @@ BOOL LogEvent(
     PSID  lpUserSid,
     LPCSTR  message)
 {
-    LPCSTR  messages[] = {message, NULL};
+    LPCSTR  messages[] = {message, nullptr};
 
     HANDLE hElog = RegisterEventSource(lpUNCServerName, "Shibboleth ISAPI Filter");
-    BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, NULL);
+    BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, nullptr);
     return (DeregisterEventSource(hElog) && res);
 }
 
+void _my_invalid_parameter_handler(
+   const wchar_t * expression,
+   const wchar_t * function,
+   const wchar_t * file,
+   unsigned int line,
+   uintptr_t pReserved
+   )
+{
+    return;
+}
+
 extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
 {
     if (fdwReason==DLL_PROCESS_ATTACH)
@@ -129,7 +139,7 @@ extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
         return FALSE;
 
     if (!g_Config) {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
                 "Extension mode startup not possible, is the DLL loaded as a filter?");
         return FALSE;
     }
@@ -149,7 +159,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
     if (!pVer)
         return FALSE;
     else if (g_Config) {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
                 "Reentrant filter initialization, ignoring...");
         return TRUE;
     }
@@ -164,32 +174,21 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         SPConfig::Handlers
         );
     if (!g_Config->init()) {
-        g_Config=NULL;
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+        g_Config=nullptr;
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
                 "Filter startup failed during library initialization, check native log for help.");
         return FALSE;
     }
 
-    LPCSTR config=getenv("SHIBSP_CONFIG");
-    if (!config)
-        config=SHIBSP_CONFIG;
-
     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);
-
-        g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
-        g_Config->getServiceProvider()->init();
+        if (!g_Config->instantiate(nullptr, true))
+            throw runtime_error("unknown error");
     }
     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,
+        g_Config=nullptr;
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, ex.what());
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
                 "Filter startup failed to load configuration, check native log for details.");
         return FALSE;
     }
@@ -199,21 +198,48 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
     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;
 
+        pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+        if (unsetValue.first)
+            g_unsetHeaderValue = unsetValue.second;
+        if (g_checkSpoofing) {
+            unsetValue = props->getString("spoofKey");
+            if (unsetValue.first)
+                g_spoofKey = unsetValue.second;
+            else {
+                _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
+                unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
+                if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
+                    _set_invalid_parameter_handler(old);
+                    ostringstream keystr;
+                    keystr << randkey << randkey2 << randkey3 << randkey4;
+                    g_spoofKey = keystr.str();
+                }
+                else {
+                    _set_invalid_parameter_handler(old);
+                    LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
+                            "Filter failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually).");
+                    locker.assign();    // pops lock on SP config
+                    g_Config->term();
+                    g_Config=nullptr;
+                    return FALSE;
+                }
+            }
+        }
+
         props = props->getPropertySet("ISAPI");
         if (props) {
             flag = props->getBool("normalizeRequest");
             g_bNormalizeRequest = !flag.first || flag.second;
+            flag = props->getBool("safeHeaderNames");
+            g_bSafeHeaderNames = flag.first && flag.second;
             const DOMElement* child = XMLHelper::getFirstChildElement(props->getElement(),Site);
             while (child) {
-                auto_ptr_char id(child->getAttributeNS(NULL,id));
+                auto_ptr_char id(child->getAttributeNS(nullptr,id));
                 if (id.get())
                     g_Sites.insert(pair<string,site_t>(id.get(),site_t(child)));
                 child=XMLHelper::getNextSiblingElement(child,Site);
@@ -228,7 +254,7 @@ 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...");
+    LogEvent(nullptr, EVENTLOG_INFORMATION_TYPE, 7701, nullptr, "Filter initialized...");
     return TRUE;
 }
 
@@ -236,8 +262,8 @@ extern "C" BOOL WINAPI TerminateFilter(DWORD)
 {
     if (g_Config)
         g_Config->term();
-    g_Config = NULL;
-    LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter shut down...");
+    g_Config = nullptr;
+    LogEvent(nullptr, EVENTLOG_INFORMATION_TYPE, 7701, nullptr, "Filter shut down...");
     return TRUE;
 }
 
@@ -254,7 +280,7 @@ extern "C" BOOL WINAPI TerminateFilter(DWORD)
 class dynabuf
 {
 public:
-    dynabuf() { bufptr=NULL; buflen=0; }
+    dynabuf() { bufptr=nullptr; buflen=0; }
     dynabuf(size_t s) { bufptr=new char[buflen=s]; *bufptr=0; }
     ~dynabuf() { delete[] bufptr; }
     size_t length() const { return bufptr ? strlen(bufptr) : 0; }
@@ -285,8 +311,8 @@ void dynabuf::reserve(size_t s, bool keep)
 
 bool dynabuf::operator==(const char* s) const
 {
-    if (buflen==NULL || s==NULL)
-        return (buflen==NULL && s==NULL);
+    if (buflen==0 || s==nullptr)
+        return (buflen==0 && s==nullptr);
     else
         return strcmp(bufptr,s)==0;
 }
@@ -358,10 +384,11 @@ class ShibTargetIsapiF : public AbstractSPRequest
   string m_scheme,m_hostname;
   mutable string m_remote_addr,m_content_type,m_method;
   dynabuf m_allhttp;
+  bool m_firsttime;
 
 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) {
+      : AbstractSPRequest(SHIBSP_LOGCAT".ISAPI"), m_pfc(pfc), m_pn(pn), m_allhttp(4096), m_firsttime(true) {
 
     // URL path always come from IIS.
     dynabuf var(256);
@@ -392,13 +419,14 @@ public:
     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;
-        }
+    if (!g_spoofKey.empty()) {
+        GetHeader(pn, pfc, "ShibSpoofCheck:", var, 32, false);
+        if (!var.empty() && g_spoofKey == (char*)var)
+            m_firsttime = false;
     }
+
+    if (!m_firsttime)
+        log(SPDebug, "ISAPI filter running more than once");
   }
   ~ShibTargetIsapiF() { }
 
@@ -411,10 +439,15 @@ public:
   int getPort() const {
     return m_port;
   }
+  const char* getQueryString() const {
+      const char* uri = getRequestURI();
+      uri = (uri ? strchr(uri, '?') : nullptr);
+      return uri ? (uri + 1) : nullptr;
+  }
   const char* getMethod() const {
     if (m_method.empty()) {
         dynabuf var(5);
-        GetServerVariable(m_pfc,"REQUEST_METHOD",var,5,false);
+        GetServerVariable(m_pfc,"HTTP_METHOD",var,5,false);
         if (!var.empty())
             m_method = var;
     }
@@ -423,16 +456,14 @@ public:
   string getContentType() const {
     if (m_content_type.empty()) {
         dynabuf var(32);
-        GetServerVariable(m_pfc,"CONTENT_TYPE",var,32,false);
+        GetServerVariable(m_pfc,"HTTP_CONTENT_TYPE",var,32,false);
         if (!var.empty())
             m_content_type = var;
     }
     return m_content_type;
   }
-  long getContentLength() const {
-      return 0;
-  }
   string getRemoteAddr() const {
+    m_remote_addr = AbstractSPRequest::getRemoteAddr();
     if (m_remote_addr.empty()) {
         dynabuf var(16);
         GetServerVariable(m_pfc,"REMOTE_ADDR",var,16,false);
@@ -443,45 +474,67 @@ public:
   }
   void log(SPLogLevel level, const string& msg) {
     AbstractSPRequest::log(level,msg);
-    if (level >= SPError)
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
+    if (level >= SPCrit)
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, msg.c_str());
+  }
+  string makeSafeHeader(const char* rawname) const {
+      string hdr;
+      for (; *rawname; ++rawname) {
+          if (isalnum(*rawname))
+              hdr += *rawname;
+      }
+      return (hdr + ':');
   }
   void clearHeader(const char* rawname, const char* cginame) {
-       if (g_checkSpoofing && m_pfc->pFilterContext && !static_cast<context_t*>(m_pfc->pFilterContext)->m_checked) {
+    if (g_checkSpoofing && m_firsttime) {
         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()));
+               GetServerVariable(m_pfc, "ALL_HTTP", m_allhttp, 4096);
+        string hdr = g_bSafeHeaderNames ? ("HTTP_" + makeSafeHeader(cginame + 5)) : (string(cginame) + ':');
+        if (strstr(m_allhttp, hdr.c_str()))
+            throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, hdr.c_str()));
+    }
+    if (g_bSafeHeaderNames) {
+        string hdr = makeSafeHeader(rawname);
+        m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(g_unsetHeaderValue.c_str()));
+    }
+    else if (!strcmp(rawname,"REMOTE_USER")) {
+           m_pn->SetHeader(m_pfc, "remote-user:", const_cast<char*>(g_unsetHeaderValue.c_str()));
+        m_pn->SetHeader(m_pfc, "remote_user:", const_cast<char*>(g_unsetHeaderValue.c_str()));
+       }
+       else {
+           string hdr = string(rawname) + ':';
+           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 += ':';
+    string hdr = g_bSafeHeaderNames ? makeSafeHeader(name) : (string(name) + ':');
     m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(value));
   }
+  string getSecureHeader(const char* name) const {
+    string hdr = g_bSafeHeaderNames ? makeSafeHeader(name) : (string(name) + ':');
+    dynabuf buf(256);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 256, false);
+    return string(buf.empty() ? "" : buf);
+  }
   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);
+    return string(buf.empty() ? "" : 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);
-    }
+    if (!user || !*user)
+        m_pfc->pFilterContext = nullptr;
+    else if (m_pfc->pFilterContext = m_pfc->AllocMem(m_pfc, sizeof(char) * (strlen(user) + 1), 0))
+        strcpy(reinterpret_cast<char*>(m_pfc->pFilterContext), user);
   }
   string getRemoteUser() const {
-    return getHeader("remote-user");
+    return getSecureHeader("remote-user");
   }
   void setResponseHeader(const char* name, const char* value) {
+    HTTPResponse::setResponseHeader(name, value);
     // Set for later.
     if (value)
         m_headers.insert(make_pair(name,value));
@@ -495,6 +548,7 @@ public:
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
+        case XMLTOOLING_HTTP_STATUS_NOTMODIFIED:    codestr="304 Not Modified"; break;
         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;
@@ -510,7 +564,7 @@ public:
     return SF_STATUS_REQ_FINISHED;
   }
   long sendRedirect(const char* url) {
-    // XXX: Don't support the httpRedirect option, yet.
+    HTTPResponse::sendRedirect(url);
     string hdr=string("Location: ") + url + "\r\n"
       "Content-Type: text/html\r\n"
       "Content-Length: 40\r\n"
@@ -537,13 +591,13 @@ public:
   }
 
   // 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"); }
+  long getContentLength() const { throw IOException("The request's Content-Length is not available to an ISAPI filter."); }
+  const char* getRequestBody() const { throw IOException("The request body is not available to an ISAPI filter."); }
 };
 
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
 {
-    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, 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>"
@@ -562,8 +616,8 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 {
     // Is this a log notification?
     if (notificationType==SF_NOTIFY_LOG) {
-        if (pfc->pFilterContext && static_cast<context_t*>(pfc->pFilterContext)->m_user)
-               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast<context_t*>(pfc->pFilterContext)->m_user;
+        if (pfc->pFilterContext)
+               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=reinterpret_cast<char*>(pfc->pFilterContext);
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
 
@@ -587,8 +641,8 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 
         // "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 (!g_spoofKey.empty())
+            pn->SetHeader(pfc, "ShibSpoofCheck:", const_cast<char*>(g_spoofKey.c_str()));
         if (res.first) return res.second;
 
         // "false" because we don't override the Shib settings
@@ -610,11 +664,11 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
             return WriteClientError(pfc,"Shibboleth Filter detected unexpected IIS error.");
     }
     catch (exception& e) {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, 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.");
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, "Shibboleth Filter threw an unknown exception.");
         if (g_catchAll)
             return WriteClientError(pfc,"Shibboleth Filter threw an unknown exception.");
         throw;
@@ -629,7 +683,7 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 
 DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
 {
-    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, 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>";
@@ -764,6 +818,7 @@ public:
     return m_remote_user;
   }
   string getRemoteAddr() const {
+    m_remote_addr = AbstractSPRequest::getRemoteAddr();
     if (m_remote_addr.empty()) {
         dynabuf var(16);
         GetServerVariable(m_lpECB, "REMOTE_ADDR", var, 16, false);
@@ -774,8 +829,8 @@ public:
   }
   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());
+      if (level >= SPCrit)
+          LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, msg.c_str());
   }
   string getHeader(const char* name) const {
     string hdr("HTTP_");
@@ -790,6 +845,7 @@ public:
     return buf.empty() ? "" : buf;
   }
   void setResponseHeader(const char* name, const char* value) {
+    HTTPResponse::setResponseHeader(name, value);
     // Set for later.
     if (value)
         m_headers.insert(make_pair(name,value));
@@ -806,13 +862,22 @@ public:
         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;
+      if (m_lpECB->cbAvailable > 0) {
+        m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
+        datalen-=m_lpECB->cbAvailable;
+      }
+      char buf[8192];
       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.");
+        if (!ret) {
+            char message[65];
+            _snprintf(message, 64, "Error reading request body from browser (%x).", GetLastError());
+            throw IOException(message);
+        }
+        else if (!buflen)
+            throw IOException("Socket closed while reading request body from browser.");
         m_body.append(buf, buflen);
         datalen-=buflen;
       }
@@ -830,6 +895,7 @@ public:
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
+        case XMLTOOLING_HTTP_STATUS_NOTMODIFIED:    codestr="304 Not Modified"; break;
         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;
@@ -845,6 +911,7 @@ public:
     return HSE_STATUS_SUCCESS;
   }
   long sendRedirect(const char* url) {
+    HTTPResponse::sendRedirect(url);
     string hdr=string("Location: ") + url + "\r\n"
       "Content-Type: text/html\r\n"
       "Content-Length: 40\r\n"
@@ -880,12 +947,16 @@ public:
         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 (m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_GET_CERT_INFO_EX, (LPVOID)&ccex, (LPDWORD)dwSize, nullptr)) {
             if (ccex.CertContext.cbCertEncoded) {
-                unsigned int outlen;
+                xsecsize_t outlen;
                 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(CertificateBuf), ccex.CertContext.cbCertEncoded, &outlen);
                 m_certs.push_back(reinterpret_cast<char*>(serialized));
+#ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
                 XMLString::release(&serialized);
+#else
+                XMLString::release((char**)&serialized);
+#endif
             }
         }
       }
@@ -912,7 +983,7 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
         // 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).");
+            return WriteClientError(lpECB, "Shibboleth Extension not configured for web site (check ISAPI mappings in SP configuration).");
 
         ShibTargetIsapiE ste(lpECB, map_i->second);
         pair<bool,long> res = ste.getServiceProvider().doHandler(ste);
@@ -931,11 +1002,11 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
             return WriteClientError(lpECB,"Server detected unexpected IIS error.");
     }
     catch (exception& e) {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, 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.");
+        LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, "Shibboleth Extension threw an unknown exception.");
         if (g_catchAll)
             return WriteClientError(lpECB,"Shibboleth Extension threw an unknown exception.");
         throw;