New -lite library and elimination of SAML libraries from modules.
[shibboleth/cpp-sp.git] / isapi_shib / isapi_shib.cpp
index 1b71250..55ab971 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2005 Internet2
+ *  Copyright 2001-2007 Internet2
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #define _CRT_NONSTDC_NO_DEPRECATE 1
 #define _CRT_SECURE_NO_DEPRECATE 1
 
+#include <shibsp/AbstractSPRequest.h>
 #include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.h>
+#include <xmltooling/unicode.h>
+#include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <xercesc/util/XMLUniDefs.hpp>
 
-// SAML Runtime
-#include <saml/saml.h>
-#include <shib/shib.h>
-#include <shib-target/shib-target.h>
-
+#include <set>
 #include <sstream>
 #include <fstream>
 #include <process.h>
 
+#include <windows.h>
 #include <httpfilt.h>
 #include <httpext.h>
 
 using namespace shibsp;
-using namespace shibtarget;
 using namespace xmltooling;
+using namespace xercesc;
 using namespace std;
 
 // globals
 namespace {
+    static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);
+    static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
     static const XMLCh name[] =             UNICODE_LITERAL_4(n,a,m,e);
     static const XMLCh port[] =             UNICODE_LITERAL_4(p,o,r,t);
     static const XMLCh sslport[] =          UNICODE_LITERAL_7(s,s,l,p,o,r,t);
@@ -83,7 +89,7 @@ namespace {
     };
     
     HINSTANCE g_hinstDLL;
-    ShibTargetConfig* g_Config = NULL;
+    SPConfig* g_Config = NULL;
     map<string,site_t> g_Sites;
     bool g_bNormalizeRequest = true;
 }
@@ -140,65 +146,65 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         return TRUE;
     }
 
-#ifndef _DEBUG
-    try
-    {
-#endif
-        LPCSTR schemadir=getenv("SHIBSCHEMAS");
-        if (!schemadir)
-            schemadir=SHIB_SCHEMAS;
-        LPCSTR config=getenv("SHIBCONFIG");
-        if (!config)
-            config=SHIB_CONFIG;
-        g_Config=&ShibTargetConfig::getConfig();
-        SPConfig::getConfig().setFeatures(
-            SPConfig::Listener |
-            SPConfig::Caching |
-            SPConfig::Metadata |
-            SPConfig::AAP |
-            SPConfig::RequestMapping |
-            SPConfig::InProcess |
-            SPConfig::Logging
-            );
-        if (!g_Config->init(schemadir)) {
-            g_Config=NULL;
-            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
-                    "Filter startup failed during library initialization, check native log for help.");
-            return FALSE;
-        }
-        else if (!g_Config->load(config)) {
-            g_Config=NULL;
-            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
-                    "Filter startup failed to load configuration, check native log for help.");
-            return FALSE;
-        }
-        
-        // Access the implementation-specifics for site mappings.
-        IConfig* conf=g_Config->getINI();
-        xmltooling::Locker locker(conf);
-        const PropertySet* props=conf->getPropertySet("Local");
-        if (props) {
-            const DOMElement* impl=XMLHelper::getFirstChildElement(props->getElement(),Implementation);
-            if (impl && (impl=XMLHelper::getFirstChildElement(impl,ISAPI))) {
-                const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest);
-                g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t);
-                impl=XMLHelper::getFirstChildElement(impl,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=XMLHelper::getNextSiblingElement(impl,Site);
-                }
-            }
-        }
-#ifndef _DEBUG
+    LPCSTR schemadir=getenv("SHIBSP_SCHEMAS");
+    if (!schemadir)
+        schemadir=SHIBSP_SCHEMAS;
+    LPCSTR config=getenv("SHIBSP_CONFIG");
+    if (!config)
+        config=SHIBSP_CONFIG;
+    g_Config=&SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging
+        );
+    if (!g_Config->init(schemadir)) {
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed during library initialization, check native log for help.");
+        return FALSE;
     }
-    catch (...)
-    {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with an exception.");
+
+    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();
+    }
+    catch (exception& ex) {
+        g_Config->term();
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, ex.what());
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed to load configuration, check native log for details.");
         return FALSE;
     }
-#endif
+    
+    // Access the implementation-specifics for site mappings.
+    ServiceProvider* sp=g_Config->getServiceProvider();
+    xmltooling::Locker locker(sp);
+    const PropertySet* props=sp->getPropertySet("Local");
+    if (props) {
+        const DOMElement* impl=XMLHelper::getFirstChildElement(props->getElement(),Implementation);
+        if (impl && (impl=XMLHelper::getFirstChildElement(impl,ISAPI))) {
+            const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest);
+            g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t);
+            impl=XMLHelper::getFirstChildElement(impl,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=XMLHelper::getNextSiblingElement(impl,Site);
+            }
+        }
+    }
 
     pVer->dwFilterVersion=HTTP_FILTER_REVISION;
     strncpy(pVer->lpszFilterDesc,"Shibboleth ISAPI Filter",SF_MAX_FILTER_DESC_LEN);
@@ -214,7 +220,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
 extern "C" BOOL WINAPI TerminateFilter(DWORD)
 {
     if (g_Config)
-        g_Config->shutdown();
+        g_Config->term();
     g_Config = NULL;
     LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter shut down...");
     return TRUE;
@@ -328,12 +334,15 @@ void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
 /****************************************************************************/
 // ISAPI Filter
 
-class ShibTargetIsapiF : public ShibTarget
+class ShibTargetIsapiF : public AbstractSPRequest
 {
   PHTTP_FILTER_CONTEXT m_pfc;
   PHTTP_FILTER_PREPROC_HEADERS m_pn;
   map<string,string> m_headers;
-  vector<XSECCryptoX509*> m_certs;
+  vector<string> m_certs;
+  int m_port;
+  string m_scheme,m_hostname,m_uri;
+  mutable string m_remote_addr,m_content_type,m_method;
 
 public:
   ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site) {
@@ -342,40 +351,33 @@ public:
     m_pn = pn;
 
     // URL path always come from IIS.
-    dynabuf url(256);
-    GetHeader(pn,pfc,"url",url,256,false);
+    dynabuf var(256);
+    GetHeader(pn,pfc,"url",var,256,false);
+    m_uri = var;
 
     // Port may come from IIS or from site def.
-    dynabuf port(11);
-    if (!g_bNormalizeRequest || (pfc->fIsSecurePort && site.m_sslport.empty()) || (!pfc->fIsSecurePort && site.m_port.empty()))
-        GetServerVariable(pfc,"SERVER_PORT",port,10);
+    if (!g_bNormalizeRequest || (pfc->fIsSecurePort && site.m_sslport.empty()) || (!pfc->fIsSecurePort && site.m_port.empty())) {
+        GetServerVariable(pfc,"SERVER_PORT",var,10);
+        m_port = atoi(var);
+    }
     else if (pfc->fIsSecurePort) {
-        strncpy(port,site.m_sslport.c_str(),10);
-        static_cast<char*>(port)[10]=0;
+        m_port = atoi(site.m_sslport.c_str());
     }
     else {
-        strncpy(port,site.m_port.c_str(),10);
-        static_cast<char*>(port)[10]=0;
+        m_port = atoi(site.m_port.c_str());
     }
     
     // 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";
+    m_scheme=site.m_scheme;
+    if (m_scheme.empty() || !g_bNormalizeRequest)
+        m_scheme=pfc->fIsSecurePort ? "https" : "http";
 
-    // Get the rest of the server variables.
-    dynabuf remote_addr(16),method(5),content_type(32),hostname(32);
-    GetServerVariable(pfc,"SERVER_NAME",hostname,32);
-    GetServerVariable(pfc,"REMOTE_ADDR",remote_addr,16);
-    GetServerVariable(pfc,"REQUEST_METHOD",method,5,false);
-    GetServerVariable(pfc,"CONTENT_TYPE",content_type,32,false);
+    GetServerVariable(pfc,"SERVER_NAME",var,32);
 
     // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
-    const char* host=hostname;
-    if (site.m_name!=host && site.m_aliases.find(host)==site.m_aliases.end())
-        host=site.m_name.c_str();
-
-    init(scheme, host, atoi(port), url, content_type, remote_addr, method); 
+    m_hostname = var;
+    if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+        m_hostname=site.m_name;
   }
   ~ShibTargetIsapiF() { }
 
@@ -392,15 +394,33 @@ public:
     return m_uri.c_str();
   }
   const char* getMethod() const {
+    if (m_method.empty()) {
+        dynabuf var(5);
+        GetServerVariable(m_pfc,"REQUEST_METHOD",var,5,false);
+        if (!var.empty())
+            m_method = var;
+    }
     return m_method.c_str();
   }
   string getContentType() const {
+    if (m_content_type.empty()) {
+        dynabuf var(32);
+        GetServerVariable(m_pfc,"CONTENT_TYPE",var,32,false);
+        if (!var.empty())
+            m_content_type = var;
+    }
     return m_content_type;
   }
   long getContentLength() const {
       return 0;
   }
   string getRemoteAddr() const {
+    if (m_remote_addr.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_pfc,"REMOTE_ADDR",var,16,false);
+        if (!var.empty())
+            m_remote_addr = var;
+    }
     return m_remote_addr;
   }
   void log(SPLogLevel level, const string& msg) {
@@ -445,9 +465,9 @@ public:
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
-        case SAML_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
-        case SAML_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
-        case SAML_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
     }
     m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, (void*)codestr, (DWORD)hdr.c_str(), 0);
     char buf[1024];
@@ -474,19 +494,20 @@ public:
     m_pfc->WriteClient(m_pfc, (LPVOID)redmsg, &resplen, 0);
     return SF_STATUS_REQ_FINISHED;
   }
-  // XXX: We might not ever hit the 'decline' status in this filter.
-  //long returnDecline(void) { }
-  long returnOK(void) {
+  long returnDecline() {
+      return SF_STATUS_REQ_NEXT_NOTIFICATION;
+  }
+  long returnOK() {
     return SF_STATUS_REQ_NEXT_NOTIFICATION;
   }
 
-  const vector<XSECCryptoX509*>& getClientCertificates() const {
+  const vector<string>& getClientCertificates() const {
       return m_certs;
   }
   
   // The filter never processes the POST, so stub these methods.
-  const char* getQueryString() const { throw runtime_error("getQueryString not implemented"); }
-  const char* getRequestBody() const { throw runtime_error("getRequestBody not implemented"); }
+  const char* getQueryString() const { throw IOException("getQueryString not implemented"); }
+  const char* getRequestBody() const { throw IOException("getRequestBody not implemented"); }
 };
 
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
@@ -535,14 +556,14 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
         ShibTargetIsapiF stf(pfc, pn, map_i->second);
 
         // "false" because we don't override the Shib settings
-        pair<bool,long> res = stf.doCheckAuthN();
+        pair<bool,long> res = stf.getServiceProvider().doAuthentication(stf);
         if (res.first) return res.second;
 
         // "false" because we don't override the Shib settings
-        res = stf.doExportAssertions();
+        res = stf.getServiceProvider().doExport(stf);
         if (res.first) return res.second;
 
-        res = stf.doCheckAuthZ();
+        res = stf.getServiceProvider().doAuthorization(stf);
         if (res.first) return res.second;
 
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
@@ -590,13 +611,16 @@ DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
 }
 
 
-class ShibTargetIsapiE : public ShibTarget
+class ShibTargetIsapiE : public AbstractSPRequest
 {
   LPEXTENSION_CONTROL_BLOCK m_lpECB;
   map<string,string> m_headers;
-  vector<XSECCryptoX509*> m_certs;
+  vector<string> m_certs;
   mutable string m_body;
   mutable bool m_gotBody;
+  int m_port;
+  string m_scheme,m_hostname,m_uri;
+  mutable string m_remote_addr;
   
 public:
   ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site) : m_lpECB(lpECB), m_gotBody(false) {
@@ -604,6 +628,11 @@ public:
     GetServerVariable(lpECB,"HTTPS",ssl,5);
     bool SSL=(ssl=="on" || ssl=="ON");
 
+    // Scheme may come from site def or be derived from IIS.
+    m_scheme=site.m_scheme;
+    if (m_scheme.empty() || !g_bNormalizeRequest)
+        m_scheme = SSL ? "https" : "http";
+
     // URL path always come from IIS.
     dynabuf url(256);
     GetServerVariable(lpECB,"URL",url,255);
@@ -620,22 +649,15 @@ public:
         strncpy(port,site.m_port.c_str(),10);
         static_cast<char*>(port)[10]=0;
     }
+    m_port = atoi(port);
 
-    // 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 other server variables.
-    dynabuf remote_addr(16),hostname(32);
-    GetServerVariable(lpECB, "REMOTE_ADDR", remote_addr, 16);
-    GetServerVariable(lpECB, "SERVER_NAME", hostname, 32);
+    dynabuf var(32);
+    GetServerVariable(lpECB, "SERVER_NAME", var, 32);
 
     // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
-    const char* host=hostname;
-    if (site.m_name!=host && site.m_aliases.find(host)==site.m_aliases.end())
-        host=site.m_name.c_str();
+    m_hostname=var;
+    if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+        m_hostname=site.m_name;
 
     /*
      * IIS screws us over on PATH_INFO (the hits keep on coming). We need to figure out if
@@ -654,25 +676,22 @@ public:
      *      PathInfo:   /SAML/POST
      */
     
-    string fullurl;
-    
     // Clearly we're only in bad mode if path info exists at all.
     if (lpECB->lpszPathInfo && *(lpECB->lpszPathInfo)) {
         if (strstr(lpECB->lpszPathInfo,url))
             // Pretty good chance we're in bad mode, unless the PathInfo repeats the path itself.
-            fullurl=lpECB->lpszPathInfo;
+            m_uri = lpECB->lpszPathInfo;
         else {
-            fullurl+=url;
-            fullurl+=lpECB->lpszPathInfo;
+            m_uri = url;
+            m_uri += lpECB->lpszPathInfo;
         }
     }
     
     // For consistency with Apache, let's add the query string.
     if (lpECB->lpszQueryString && *(lpECB->lpszQueryString)) {
-        fullurl+='?';
-        fullurl+=lpECB->lpszQueryString;
+        m_uri += '?';
+        m_uri += lpECB->lpszQueryString;
     }
-    init(scheme, host, atoi(port), fullurl.c_str(), lpECB->lpszContentType, remote_addr, lpECB->lpszMethod);
   }
   ~ShibTargetIsapiE() { }
 
@@ -689,7 +708,7 @@ public:
     return m_uri.c_str();
   }
   const char* getMethod() const {
-    return m_lpECB->lpszMethod ? m_lpECB->lpszMethod : "";
+    return m_lpECB->lpszMethod;
   }
   string getContentType() const {
     return m_lpECB->lpszContentType ? m_lpECB->lpszContentType : "";
@@ -698,6 +717,12 @@ public:
       return m_lpECB->cbTotalBytes;
   }
   string getRemoteAddr() const {
+    if (m_remote_addr.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_lpECB, "REMOTE_ADDR", var, 16, false);
+        if (!var.empty())
+            m_remote_addr = var;
+    }
     return m_remote_addr;
   }
   void log(SPLogLevel level, const string& msg) {
@@ -731,8 +756,8 @@ public:
     if (m_gotBody)
         return m_body.c_str();
     if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB?
-        throw opensaml::BindingException("Size of POST request body exceeded limit.");
-    else if (m_lpECB->cbTotalBytes != m_lpECB->cbAvailable) {
+        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;
@@ -740,12 +765,12 @@ public:
         DWORD buflen=8192;
         BOOL ret = m_lpECB->ReadClient(m_lpECB->ConnID, buf, &buflen);
         if (!ret || !buflen)
-            throw saml::SAMLException("Error reading POST request body from browser.");
+            throw IOException("Error reading request body from browser.");
         m_body.append(buf, buflen);
         datalen-=buflen;
       }
     }
-    else {
+    else if (m_lpECB->cbAvailable) {
         m_gotBody=true;
         m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
     }
@@ -758,9 +783,9 @@ public:
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
-        case SAML_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
-        case SAML_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
-        case SAML_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
     }
     m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, (void*)codestr, 0, (LPDWORD)hdr.c_str());
     char buf[1024];
@@ -799,7 +824,7 @@ public:
       return HSE_STATUS_SUCCESS;
   }
 
-  const vector<XSECCryptoX509*>& getClientCertificates() const {
+  const vector<string>& getClientCertificates() const {
       return m_certs;
   }
 
@@ -812,8 +837,6 @@ public:
 
 extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
 {
-    string targeturl;
-    const IApplication* application=NULL;
     try {
         ostringstream threadid;
         threadid << "[" << getpid() << "] isapi_shib_extension" << '\0';
@@ -829,7 +852,7 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
             return WriteClientError(lpECB, "Shibboleth Extension not configured for this web site.");
 
         ShibTargetIsapiE ste(lpECB, map_i->second);
-        pair<bool,long> res = ste.doHandler();
+        pair<bool,long> res = ste.getServiceProvider().doHandler(ste);
         if (res.first) return res.second;
         
         return WriteClientError(lpECB, "Shibboleth Extension failed to process request");