Null pointer bug.
[shibboleth/sp.git] / isapi_shib / isapi_shib.cpp
index fadd2ad..e12c1cd 100644 (file)
@@ -164,8 +164,10 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         return TRUE;
     }
 
+#ifndef _DEBUG
     try
     {
+#endif
         LPCSTR schemadir=getenv("SHIBSCHEMAS");
         if (!schemadir)
             schemadir=SHIB_SCHEMAS;
@@ -178,7 +180,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
             ShibTargetConfig::Metadata |
             ShibTargetConfig::AAP |
             ShibTargetConfig::RequestMapper |
-            ShibTargetConfig::SHIREExtensions |
+            ShibTargetConfig::LocalExtensions |
             ShibTargetConfig::Logging
             );
         if (!g_Config->init(schemadir,config)) {
@@ -191,7 +193,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         // Access the implementation-specifics for site mappings.
         IConfig* conf=g_Config->getINI();
         Locker locker(conf);
-        const IPropertySet* props=conf->getPropertySet("SHIRE");
+        const IPropertySet* props=conf->getPropertySet("Local");
         if (props) {
             const DOMElement* impl=saml::XML::getFirstChildElement(
                 props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
@@ -208,15 +210,14 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
                 }
             }
         }
+#ifndef _DEBUG
     }
     catch (...)
     {
         LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with an exception.");
-#ifdef _DEBUG
-        throw;
-#endif
         return FALSE;
     }
+#endif
 
     pVer->dwFilterVersion=HTTP_FILTER_REVISION;
     strncpy(pVer->lpszFilterDesc,"Shibboleth ISAPI Filter",SF_MAX_FILTER_DESC_LEN);
@@ -355,7 +356,7 @@ void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
 class ShibTargetIsapiF : public ShibTarget
 {
 public:
-  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPRC_HEADERS pn,
+  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn,
                   const site_t& site) {
 
     // URL path always come from IIS.
@@ -382,6 +383,8 @@ public:
 
     // 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
@@ -393,20 +396,17 @@ public:
   ~ShibTargetIsapiF() { }
 
   virtual void log(ShibLogLevel level, const string &msg) {
-    LogEvent(NULL, (level == LogLevelDebug : EVENTLOG_DEBUG_TYPE ?
-                   (level == LogLevelInfo : EVENTLOG_INFORMATION_TYPE ?
-                    (level == LogLevelWarn : EVENTLOG_WARNING_TYPE ?
-                     EVENTLOG_ERROR_TYPE))),
+      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;
   }
-  // XXX: the filter never processes the POST.
-  //virtual void setCookie(const string &name, const string &value) {  }
-  //virtual string getArgs(void) {  }
-  //virtual string getPostData(void) {  }
+  
   virtual void clearHeader(const string &name) {
     string hdr = name + ":";
     m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), "");
@@ -419,7 +419,7 @@ public:
   virtual string getHeader(const string &name) {
     string hdr = name + ":";
     dynabuf buf(1024);
-    GetHeader(m_pn, m_pfc, hdr.c_str(), buf, 1024, false);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 1024, false);
     return string(buf);
   }
   virtual void setRemoteUser(const string &user) {
@@ -429,15 +429,15 @@ public:
     return getHeader(string("remote-user"));
   }
   virtual void* sendPage(const string &msg, const string content_type,
-                        const pair<string, string> headers[], int code) {
+      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";
+    while (headers.hasNext()) {
+        const header_t& h=headers.next();
+        hdr += h.first + ": " + h.second + "\r\n";
     }
     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);
+    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;
@@ -454,16 +454,99 @@ public:
     static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
     DWORD resplen=40;
     m_pfc->WriteClient(m_pfc, (LPVOID)redmsg, &resplen, 0);
-    return SF_STATUS_REQ_FINISHED;
+    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_PREPRC_HEADERS m_pn
+  PHTTP_FILTER_PREPROC_HEADERS m_pn;
 };
 
+DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
+{
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
+    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);
+    pfc->WriteClient(pfc,(LPVOID)xmsg,&resplen,0);
+    resplen=strlen(msg);
+    pfc->WriteClient(pfc,(LPVOID)msg,&resplen,0);
+    static const char* xmsg2="</BODY></HTML>";
+    resplen=strlen(xmsg2);
+    pfc->WriteClient(pfc,(LPVOID)xmsg2,&resplen,0);
+    return SF_STATUS_REQ_FINISHED;
+}
+
+extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification)
+{
+    // Is this a log notification?
+    if (notificationType==SF_NOTIFY_LOG)
+    {
+        if (pfc->pFilterContext)
+            ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast<LPCSTR>(pfc->pFilterContext);
+        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() << "] isapi_shib" << '\0';
+        saml::NDC ndc(threadid.str().c_str());
+
+       ShibTargetIsapiF stf(pfc, pn, map_i->second);
+
+       // "false" because we don't override the Shib settings
+       pair<bool,void*> res = stf.doCheckAuthN();
+       if (res.first) return (DWORD)res.second;
+
+       // "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
     )
@@ -507,23 +590,6 @@ IRequestMapper::Settings map_request(
     return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
 }
 
-DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
-{
-    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
-    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
-    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);
-    pfc->WriteClient(pfc,(LPVOID)xmsg,&resplen,0);
-    resplen=strlen(msg);
-    pfc->WriteClient(pfc,(LPVOID)msg,&resplen,0);
-    static const char* xmsg2="</BODY></HTML>";
-    resplen=strlen(xmsg2);
-    pfc->WriteClient(pfc,(LPVOID)xmsg2,&resplen,0);
-    return SF_STATUS_REQ_FINISHED;
-}
-
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* page, ShibMLP& mlp)
 {
     const IPropertySet* props=app->getPropertySet("Errors");
@@ -922,7 +988,189 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 
     return WriteClientError(pfc,"Server reached unreachable code, save my walrus!");
 }
+#endif // 0
+
+/****************************************************************************/
+// ISAPI Extension
+
+DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
+{
+    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
+    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)ctype);
+    static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Error</TITLE></HEAD><BODY><H1>Shibboleth Error</H1>";
+    DWORD resplen=strlen(xmsg);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg,&resplen,HSE_IO_SYNC);
+    resplen=strlen(msg);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)msg,&resplen,HSE_IO_SYNC);
+    static const char* xmsg2="</BODY></HTML>";
+    resplen=strlen(xmsg2);
+    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg2,&resplen,HSE_IO_SYNC);
+    return HSE_STATUS_SUCCESS;
+}
+
+
+class ShibTargetIsapiE : public ShibTarget
+{
+public:
+  ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site)
+  {
+    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";
+    }
+
+    // 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);
+        GetServerVariable(lpECB,"INSTANCE_ID",buf,10);
+
+        // Match site instance to host name, skip if no match.
+        map<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
+        if (map_i==g_Sites.end())
+            return WriteClientError(lpECB, "Shibboleth Extension not configured for 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 request");
+
+    }
+    catch (...) {
+      return WriteClientError(lpECB,
+                             "Shibboleth Extension caught an unknown error.");
+    }
+
+    // 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
     )
@@ -971,22 +1219,6 @@ IRequestMapper::Settings map_request(
     return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
 }
 
-DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
-{
-    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
-    static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
-    lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)ctype);
-    static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Error</TITLE></HEAD><BODY><H1>Shibboleth Error</H1>";
-    DWORD resplen=strlen(xmsg);
-    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg,&resplen,HSE_IO_SYNC);
-    resplen=strlen(msg);
-    lpECB->WriteClient(lpECB->ConnID,(LPVOID)msg,&resplen,HSE_IO_SYNC);
-    static const char* xmsg2="</BODY></HTML>";
-    resplen=strlen(xmsg2);
-    lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg2,&resplen,HSE_IO_SYNC);
-    return HSE_STATUS_SUCCESS;
-}
-
 DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* page, ShibMLP& mlp)
 {
     const IPropertySet* props=app->getPropertySet("Errors");
@@ -1254,6 +1486,7 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
         }
     }
 #endif
-    
+
     return HSE_STATUS_ERROR;
 }
+#endif // 0