Merge commit '2.5.0' into moonshot-packaging-fixes
[shibboleth/sp.git] / isapi_shib / isapi_shib.cpp
index e8e9d93..40a248c 100644 (file)
 #include <shibsp/ServiceProvider.h>
 
 #include <set>
-#include <sstream>
 #include <fstream>
 #include <stdexcept>
 #include <process.h>
+#include <boost/lexical_cast.hpp>
 #include <xmltooling/unicode.h>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
@@ -56,6 +56,7 @@
 using namespace shibsp;
 using namespace xmltooling;
 using namespace xercesc;
+using namespace boost;
 using namespace std;
 
 // globals
@@ -72,19 +73,15 @@ namespace {
 
     struct site_t {
         site_t(const DOMElement* e)
+            : m_name(XMLHelper::getAttrString(e, "", name)),
+                m_scheme(XMLHelper::getAttrString(e, "", scheme)),
+                m_port(XMLHelper::getAttrString(e, "", port)),
+                m_sslport(XMLHelper::getAttrString(e, "", 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();
-            if (p2.get()) m_sslport=p2.get();
             e = XMLHelper::getFirstChildElement(e, Alias);
             while (e) {
                 if (e->hasChildNodes()) {
-                    auto_ptr_char alias(e->getFirstChild()->getNodeValue());
+                    auto_ptr_char alias(e->getTextContent());
                     m_aliases.insert(alias.get());
                 }
                 e = XMLHelper::getNextSiblingElement(e, Alias);
@@ -132,8 +129,8 @@ void _my_invalid_parameter_handler(
 
 extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
 {
-    if (fdwReason==DLL_PROCESS_ATTACH)
-        g_hinstDLL=hinstDLL;
+    if (fdwReason == DLL_PROCESS_ATTACH)
+        g_hinstDLL = hinstDLL;
     return TRUE;
 }
 
@@ -148,7 +145,7 @@ extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
         return FALSE;
     }
 
-    pVer->dwExtensionVersion=HSE_VERSION;
+    pVer->dwExtensionVersion = HSE_VERSION;
     strncpy(pVer->lpszExtensionDesc,"Shibboleth ISAPI Extension",HSE_MAX_EXT_DLL_NAME_LEN-1);
     return TRUE;
 }
@@ -168,7 +165,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         return TRUE;
     }
 
-    g_Config=&SPConfig::getConfig();
+    g_Config = &SPConfig::getConfig();
     g_Config->setFeatures(
         SPConfig::Listener |
         SPConfig::Caching |
@@ -178,7 +175,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         SPConfig::Handlers
         );
     if (!g_Config->init()) {
-        g_Config=nullptr;
+        g_Config = nullptr;
         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr,
                 "Filter startup failed during library initialization, check native log for help.");
         return FALSE;
@@ -188,7 +185,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         if (!g_Config->instantiate(nullptr, true))
             throw runtime_error("unknown error");
     }
-    catch (exception& ex) {
+    catch (std::exception& ex) {
         g_Config->term();
         g_Config=nullptr;
         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, ex.what());
@@ -198,16 +195,16 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
     }
 
     // Access implementation-specifics and site mappings.
-    ServiceProvider* sp=g_Config->getServiceProvider();
+    ServiceProvider* sp = g_Config->getServiceProvider();
     Locker locker(sp);
-    const PropertySet* props=sp->getPropertySet("InProcess");
+    const PropertySet* props = sp->getPropertySet("InProcess");
     if (props) {
-        pair<bool,bool> flag=props->getBool("checkSpoofing");
+        pair<bool,bool> flag = props->getBool("checkSpoofing");
         g_checkSpoofing = !flag.first || flag.second;
-        flag=props->getBool("catchAll");
+        flag = props->getBool("catchAll");
         g_catchAll = flag.first && flag.second;
 
-        pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+        pair<bool,const char*> unsetValue = props->getString("unsetHeaderValue");
         if (unsetValue.first)
             g_unsetHeaderValue = unsetValue.second;
         if (g_checkSpoofing) {
@@ -219,9 +216,8 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
                 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();
+                    g_spoofKey = lexical_cast<string>(randkey) + lexical_cast<string>(randkey2) +
+                        lexical_cast<string>(randkey3) + lexical_cast<string>(randkey4);
                 }
                 else {
                     _set_invalid_parameter_handler(old);
@@ -229,7 +225,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
                             "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;
+                    g_Config = nullptr;
                     return FALSE;
                 }
             }
@@ -241,18 +237,18 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
             g_bNormalizeRequest = !flag.first || flag.second;
             flag = props->getBool("safeHeaderNames");
             g_bSafeHeaderNames = flag.first && flag.second;
-            const DOMElement* child = XMLHelper::getFirstChildElement(props->getElement(),Site);
+            const DOMElement* child = XMLHelper::getFirstChildElement(props->getElement(), Site);
             while (child) {
-                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);
+                string id(XMLHelper::getAttrString(child, "", id));
+                if (!id.empty())
+                    g_Sites.insert(make_pair(id, site_t(child)));
+                child = XMLHelper::getNextSiblingElement(child, Site);
             }
         }
     }
 
-    pVer->dwFilterVersion=HTTP_FILTER_REVISION;
-    strncpy(pVer->lpszFilterDesc,"Shibboleth ISAPI Filter",SF_MAX_FILTER_DESC_LEN);
+    pVer->dwFilterVersion = HTTP_FILTER_REVISION;
+    strncpy(pVer->lpszFilterDesc, "Shibboleth ISAPI Filter", SF_MAX_FILTER_DESC_LEN);
     pVer->dwFlags=(SF_NOTIFY_ORDER_HIGH |
                    SF_NOTIFY_SECURE_PORT |
                    SF_NOTIFY_NONSECURE_PORT |
@@ -374,8 +370,8 @@ public:
     }
     else {
         m_hostname = var;
-        if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
-            m_hostname=site.m_name;
+        if (site.m_name != m_hostname && site.m_aliases.find(m_hostname) == site.m_aliases.end())
+            m_hostname = site.m_name;
     }
 
     if (!g_spoofKey.empty()) {
@@ -504,7 +500,7 @@ public:
   }
   long sendResponse(istream& in, long status) {
     string hdr = string("Connection: close\r\n");
-    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i = m_headers.begin(); i != m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     const char* codestr="200 OK";
@@ -531,7 +527,7 @@ public:
       "Content-Length: 40\r\n"
       "Expires: Wed, 01 Jan 1997 12:00:00 GMT\r\n"
       "Cache-Control: private,no-store,no-cache,max-age=0\r\n";
-    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i = m_headers.begin(); i != m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, "302 Please Wait", (ULONG_PTR)hdr.c_str(), 0);
@@ -562,8 +558,8 @@ public:
 
     while (!m_pfc->GetServerVariable(m_pfc,lpszVariable,s,&size)) {
         // Grumble. Check the error.
-        DWORD e=GetLastError();
-        if (e==ERROR_INSUFFICIENT_BUFFER)
+        DWORD e = GetLastError();
+        if (e == ERROR_INSUFFICIENT_BUFFER)
             s.reserve(size);
         else
             break;
@@ -579,8 +575,8 @@ public:
 
     while (!m_pn->GetHeader(m_pfc,lpszName,s,&size)) {
         // Grumble. Check the error.
-        DWORD e=GetLastError();
-        if (e==ERROR_INSUFFICIENT_BUFFER)
+        DWORD e = GetLastError();
+        if (e == ERROR_INSUFFICIENT_BUFFER)
             s.reserve(size);
         else
             break;
@@ -631,15 +627,14 @@ void GetServerVariable(PHTTP_FILTER_CONTEXT pfc, LPSTR lpszVariable, dynabuf& s,
 extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification)
 {
     // Is this a log notification?
-    if (notificationType==SF_NOTIFY_LOG) {
+    if (notificationType == SF_NOTIFY_LOG) {
         if (pfc->pFilterContext)
-               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=reinterpret_cast<char*>(pfc->pFilterContext);
+               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName = reinterpret_cast<char*>(pfc->pFilterContext);
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
 
     PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification;
-    try
-    {
+    try {
         // Determine web site number. This can't really fail, I don't think.
         dynabuf buf(128);
         GetServerVariable(pfc,"INSTANCE_ID",buf,10);
@@ -647,13 +642,13 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
             return WriteClientError(pfc, "Shibboleth Filter failed to obtain INSTANCE_ID server variable.");
 
         // 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())
+        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() << "] isapi_shib" << '\0';
-        xmltooling::NDC ndc(threadid.str().c_str());
+        string threadid("[");
+        threadid += lexical_cast<string>(getpid()) + "] isapi_shib";
+        xmltooling::NDC ndc(threadid.c_str());
 
         ShibTargetIsapiF stf(pfc, pn, map_i->second);
 
@@ -671,26 +666,26 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
     catch(bad_alloc) {
-        return WriteClientError(pfc,"Out of Memory");
+        return WriteClientError(pfc, "Out of Memory");
     }
     catch(long e) {
         if (e==ERROR_NO_DATA)
-            return WriteClientError(pfc,"A required variable or header was empty.");
+            return WriteClientError(pfc, "A required variable or header was empty.");
         else
-            return WriteClientError(pfc,"Shibboleth Filter detected unexpected IIS error.");
+            return WriteClientError(pfc, "Shibboleth Filter detected unexpected IIS error.");
     }
-    catch (exception& e) {
+    catch (std::exception& e) {
         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, e.what());
-        return WriteClientError(pfc,"Shibboleth Filter caught an exception, check Event Log for details.");
+        return WriteClientError(pfc, "Shibboleth Filter caught an exception, check Event Log for details.");
     }
     catch(...) {
         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.");
+            return WriteClientError(pfc, "Shibboleth Filter threw an unknown exception.");
         throw;
     }
 
-    return WriteClientError(pfc,"Shibboleth Filter reached unreachable code, save my walrus!");
+    return WriteClientError(pfc, "Shibboleth Filter reached unreachable code, save my walrus!");
 }
 
 
@@ -733,7 +728,7 @@ public:
     bool SSL=(ssl=="on" || ssl=="ON");
 
     // Scheme may come from site def or be derived from IIS.
-    m_scheme=site.m_scheme;
+    m_scheme = site.m_scheme;
     if (m_scheme.empty() || !g_bNormalizeRequest)
         m_scheme = SSL ? "https" : "http";
 
@@ -767,8 +762,8 @@ public:
     else {
         // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
         m_hostname=var;
-        if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
-            m_hostname=site.m_name;
+        if (site.m_name != m_hostname && site.m_aliases.find(m_hostname) == site.m_aliases.end())
+            m_hostname = site.m_name;
     }
 
     /*
@@ -813,7 +808,7 @@ public:
 
     setRequestURI(uri.c_str());
   }
-  ~ShibTargetIsapiE() { }
+  ~ShibTargetIsapiE() {}
 
   const char* getScheme() const {
     return m_scheme.c_str();
@@ -860,7 +855,7 @@ public:
   string getHeader(const char* name) const {
     string hdr("HTTP_");
     for (; *name; ++name) {
-        if (*name=='-')
+        if (*name == '-')
             hdr += '_';
         else
             hdr += toupper(*name);
@@ -915,7 +910,7 @@ public:
   }
   long sendResponse(istream& in, long status) {
     string hdr = string("Connection: close\r\n");
-    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i = m_headers.begin(); i != m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     const char* codestr="200 OK";
@@ -942,7 +937,7 @@ public:
       "Content-Length: 40\r\n"
       "Expires: Wed, 01 Jan 1997 12:00:00 GMT\r\n"
       "Cache-Control: private,no-store,no-cache,max-age=0\r\n";
-    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i = m_headers.begin(); i != m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, "302 Moved", 0, (LPDWORD)hdr.c_str());
@@ -951,7 +946,7 @@ public:
     m_lpECB->WriteClient(m_lpECB->ConnID, (LPVOID)redmsg, &resplen, HSE_IO_SYNC);
     return HSE_STATUS_SUCCESS;
   }
-  // Decline happens in the POST processor if this isn't the shire url
+  // Decline happens in the POST processor if this isn't the handler url
   // Note that it can also happen with HTAccess, but we don't support that, yet.
   long returnDecline() {
     return WriteClientError(
@@ -1034,9 +1029,9 @@ void GetServerVariable(LPEXTENSION_CONTROL_BLOCK lpECB, LPSTR lpszVariable, dyna
 extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
 {
     try {
-        ostringstream threadid;
-        threadid << "[" << getpid() << "] isapi_shib_extension" << '\0';
-        xmltooling::NDC ndc(threadid.str().c_str());
+        string threadid("[");
+        threadid += lexical_cast<string>(getpid()) + "] isapi_shib_extension";
+        xmltooling::NDC ndc(threadid.c_str());
 
         // Determine web site number. This can't really fail, I don't think.
         dynabuf buf(128);
@@ -1045,8 +1040,8 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
             return WriteClientError(lpECB, "Shibboleth Extension failed to obtain INSTANCE_ID server variable.");
 
         // 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())
+        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 SP configuration).");
 
         ShibTargetIsapiE ste(lpECB, map_i->second);
@@ -1057,22 +1052,22 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
 
     }
     catch(bad_alloc) {
-        return WriteClientError(lpECB,"Out of Memory");
+        return WriteClientError(lpECB, "Out of Memory");
     }
     catch(long e) {
         if (e==ERROR_NO_DATA)
-            return WriteClientError(lpECB,"A required variable or header was empty.");
+            return WriteClientError(lpECB, "A required variable or header was empty.");
         else
-            return WriteClientError(lpECB,"Server detected unexpected IIS error.");
+            return WriteClientError(lpECB, "Server detected unexpected IIS error.");
     }
-    catch (exception& e) {
+    catch (std::exception& e) {
         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, e.what());
-        return WriteClientError(lpECB,"Shibboleth Extension caught an exception, check Event Log for details.");
+        return WriteClientError(lpECB, "Shibboleth Extension caught an exception, check Event Log for details.");
     }
     catch(...) {
         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.");
+            return WriteClientError(lpECB, "Shibboleth Extension threw an unknown exception.");
         throw;
     }