SSPCPP-616 - clean up concatenated string literals
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
index 61db6d2..bbceda7 100644 (file)
@@ -1,23 +1,27 @@
-/*
- *  Copyright 2001-2009 Internet2
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
  *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * UCAID licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the
+ * License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific
+ * language governing permissions and limitations under the License.
  */
 
 /**
  * nsapi_shib.cpp
  *
- * Shibboleth NSAPI filter
+ * Shibboleth NSAPI filter.
  */
 
 #define SHIBSP_LITE
@@ -43,8 +47,8 @@
 #include <set>
 #include <memory>
 #include <fstream>
-#include <sstream>
 #include <stdexcept>
+#include <boost/lexical_cast.hpp>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/Threads.h>
@@ -69,6 +73,7 @@ extern "C"
 
 using namespace shibsp;
 using namespace xmltooling;
+using namespace boost;
 using namespace std;
 
 // macros to output text to client
@@ -76,7 +81,7 @@ using namespace std;
     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
 
 namespace {
-    SPConfig* g_Config=NULL;
+    SPConfig* g_Config=nullptr;
     string g_ServerName;
     string g_unsetHeaderValue;
     string g_spoofKey;
@@ -103,7 +108,7 @@ extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
 {
     if (g_Config)
         g_Config->term();
-    g_Config = NULL;
+    g_Config = nullptr;
 }
 
 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
@@ -144,7 +149,7 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
         SPConfig::Handlers
         );
     if (!g_Config->init(schemadir,prefix)) {
-        g_Config=NULL;
+        g_Config=nullptr;
         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
         return REQ_ABORTED;
     }
@@ -155,14 +160,14 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
         if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
             throw runtime_error("unknown error");
     }
-    catch (exception& ex) {
+    catch (std::exception& ex) {
         pblock_nvinsert("error",ex.what(),pb);
         g_Config->term();
-        g_Config=NULL;
+        g_Config=nullptr;
         return REQ_ABORTED;
     }
 
-    daemon_atrestart(nsapi_shib_exit,NULL);
+    daemon_atrestart(nsapi_shib_exit,nullptr);
 
     ServiceProvider* sp=g_Config->getServiceProvider();
     Locker locker(sp);
@@ -186,16 +191,15 @@ extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request*
                 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);
                     pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
                     locker.assign(); // pops lock on SP config
                     g_Config->term();
-                    g_Config=NULL;
+                    g_Config=nullptr;
                     return REQ_ABORTED;
                 }
             }
@@ -223,7 +227,7 @@ public:
   Request* m_rq;
 
   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
-      : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
+      : AbstractSPRequest(SHIBSP_LOGCAT ".NSAPI"),
         m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
 
     // To determine whether SSL is active or not, we're supposed to rely
@@ -293,7 +297,7 @@ public:
     return pblock_findval("method", m_rq->reqpb);
   }
   string getContentType() const {
-    char* content_type = NULL;
+    char* content_type = nullptr;
     if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
         return "";
     return content_type ? content_type : "";
@@ -301,7 +305,7 @@ public:
   long getContentLength() const {
     if (m_gotBody)
         return m_body.length();
-    char* content_length=NULL;
+    char* content_length=nullptr;
     if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
         return 0;
     return content_length ? atoi(content_length) : 0;
@@ -321,10 +325,10 @@ public:
   const char* getRequestBody() const {
     if (m_gotBody)
         return m_body.c_str();
-    char* content_length=NULL;
+    char* content_length=nullptr;
     if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
         m_gotBody = true;
-        return NULL;
+        return nullptr;
     }
     else if (atoi(content_length) > 1024*1024) // 1MB?
       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
@@ -382,7 +386,7 @@ public:
   }
   string getHeader(const char* name) const {
     // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
-    char* hdr = NULL;
+    char* hdr = nullptr;
     int cookie = strcmp(name, "Cookie");
     if (cookie == 0)
         name = "cookie";
@@ -422,8 +426,10 @@ public:
       setResponseHeader("Content-Type", type);
   }
   void setResponseHeader(const char* name, const char* value) {
-    AbstractSPRequest::setResponseHeader(name, value);
-    pblock_nvinsert(name, value, m_rq->srvhdrs);
+    HTTPResponse::setResponseHeader(name, value);
+    if (name) {
+        pblock_nvinsert(name, value, m_rq->srvhdrs);
+    }
   }
 
   long sendResponse(istream& in, long status) {
@@ -435,20 +441,20 @@ public:
     }
     pblock_nvinsert("connection","close",m_rq->srvhdrs);
     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
-    protocol_status(m_sn, m_rq, status, NULL);
+    protocol_status(m_sn, m_rq, status, nullptr);
     protocol_start_response(m_sn, m_rq);
     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
     return REQ_EXIT;
   }
   long sendRedirect(const char* url) {
-    AbstractSPRequest::sendRedirect(url);
+    HTTPResponse::sendRedirect(url);
     param_free(pblock_remove("content-type", m_rq->srvhdrs));
     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
-    pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
-    pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
+    pblock_nvinsert("expires", "Wed, 01 Jan 1997 12:00:00 GMT", m_rq->srvhdrs);
+    pblock_nvinsert("cache-control", "private,no-store,no-cache,max-age=0", m_rq->srvhdrs);
     pblock_nvinsert("location", url, m_rq->srvhdrs);
     pblock_nvinsert("connection","close",m_rq->srvhdrs);
-    protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
+    protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, nullptr);
     protocol_start_response(m_sn, m_rq);
     return REQ_ABORTED;
   }
@@ -477,9 +483,9 @@ int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
 #define FUNC "shibboleth"
 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
 {
-  ostringstream threadid;
-  threadid << "[" << getpid() << "] nsapi_shib" << '\0';
-  xmltooling::NDC ndc(threadid.str().c_str());
+  string threadid("[");
+  threadid += lexical_cast<string>(getpid()) + "] nsapi_shib";
+  xmltooling::NDC ndc(threadid.c_str());
 
   try {
     ShibTargetNSAPI stn(pb, sn, rq);
@@ -506,7 +512,7 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
     // this user is ok.
     return REQ_PROCEED;
   }
-  catch (exception& e) {
+  catch (std::exception& e) {
     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
   }
@@ -523,9 +529,9 @@ extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
 #define FUNC "shib_handler"
 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
 {
-  ostringstream threadid;
-  threadid << "[" << getpid() << "] shib_handler" << '\0';
-  xmltooling::NDC ndc(threadid.str().c_str());
+  string threadid("[");
+  threadid += lexical_cast<string>(getpid()) + "] shib_handler";
+  xmltooling::NDC ndc(threadid.c_str());
 
   try {
     ShibTargetNSAPI stn(pb, sn, rq);
@@ -535,7 +541,7 @@ extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
 
     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
   }
-  catch (exception& e) {
+  catch (std::exception& e) {
     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
   }
@@ -552,26 +558,25 @@ class SunRequestMapper : public virtual RequestMapper, public virtual PropertySe
 {
 public:
     SunRequestMapper(const xercesc::DOMElement* e);
-    ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
+    ~SunRequestMapper() {}
     Lockable* lock() { return m_mapper->lock(); }
-    void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
+    void unlock() { m_stKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
     Settings getSettings(const HTTPRequest& request) const;
 
-    const PropertySet* getParent() const { return NULL; }
+    const PropertySet* getParent() const { return nullptr; }
     void setParent(const PropertySet*) {}
-    pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
-    pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
-    pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
-    pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
-    pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
+    pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
+    pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
+    pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
+    pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
+    pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
     void getAll(map<string,const char*>& properties) const;
     const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
     const xercesc::DOMElement* getElement() const;
 
 private:
-    RequestMapper* m_mapper;
-    ThreadKey* m_stKey;
-    ThreadKey* m_propsKey;
+    scoped_ptr<RequestMapper> m_mapper;
+    scoped_ptr<ThreadKey> m_stKey, m_propsKey;
 };
 
 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
@@ -579,11 +584,11 @@ RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
     return new SunRequestMapper(e);
 }
 
-SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
+SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e)
+    : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
+        m_stKey(ThreadKey::create(nullptr)),
+        m_propsKey(ThreadKey::create(nullptr))
 {
-    m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
-    m_stKey=ThreadKey::create(NULL);
-    m_propsKey=ThreadKey::create(NULL);
 }
 
 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
@@ -621,13 +626,13 @@ pair<bool,const char*> SunRequestMapper::getString(const char* name, const char*
                 return make_pair(true,param);
         }
     }
-    return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
+    return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
 }
 
 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
+    return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
 }
 
 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
@@ -637,8 +642,14 @@ pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const
     if (stn && !ns && name) {
         // Override int properties.
         const char* param=pblock_findval(name,stn->m_pb);
-        if (param)
-            return pair<bool,unsigned int>(true,strtol(param,NULL,10));
+        if (param) {
+            try {
+                return pair<bool,unsigned int>(true,lexical_cast<unsigned int>(param));
+            }
+            catch (bad_lexical_cast&) {
+                return pair<bool,unsigned int>(false,0);
+            }
+        }
     }
     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
 }
@@ -678,11 +689,11 @@ void SunRequestMapper::getAll(map<string,const char*>& properties) const
 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getPropertySet(name,ns) : NULL;
+    return s ? s->getPropertySet(name,ns) : nullptr;
 }
 
 const xercesc::DOMElement* SunRequestMapper::getElement() const
 {
     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
-    return s ? s->getElement() : NULL;
+    return s ? s->getElement() : nullptr;
 }