VS10 solution files, convert from NULL macro to nullptr.
[shibboleth/sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
index becb716..e1551cf 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  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.
  * You may obtain a copy of the License at
@@ -16,9 +16,9 @@
 
 /**
  * StorageServiceSessionCache.cpp
- * 
+ *
  * StorageService-based SessionCache implementation.
- * 
+ *
  * Instead of optimizing this plugin with a buffering scheme that keeps objects around
  * and avoids extra parsing steps, I'm assuming that systems that require such can
  * layer their own cache plugin on top of this version either by delegating to it
 #include "remoting/ListenerService.h"
 #include "util/SPConstants.h"
 
+#include <algorithm>
+#include <xmltooling/io/HTTPRequest.h>
+#include <xmltooling/io/HTTPResponse.h>
+#include <xmltooling/util/DateTime.h>
 #include <xmltooling/util/NDC.h>
+#include <xmltooling/util/ParserPool.h>
+#include <xmltooling/util/Threads.h>
 #include <xmltooling/util/XMLHelper.h>
 #include <xercesc/util/XMLUniDefs.hpp>
 
 #ifndef SHIBSP_LITE
+# include <saml/exceptions.h>
 # include <saml/SAMLConfig.h>
+# include <saml/saml2/core/Assertions.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <xmltooling/XMLToolingConfig.h>
 # include <xmltooling/util/StorageService.h>
 using namespace opensaml::saml2md;
 #else
@@ -76,15 +86,15 @@ namespace shibsp {
             const HTTPRequest& httpRequest,
             HTTPResponse& httpResponse,
             time_t expires,
-            const saml2md::EntityDescriptor* issuer=NULL,
-            const XMLCh* protocol=NULL,
-            const saml2::NameID* nameid=NULL,
-            const XMLCh* authn_instant=NULL,
-            const XMLCh* session_index=NULL,
-            const XMLCh* authncontext_class=NULL,
-            const XMLCh* authncontext_decl=NULL,
-            const vector<const Assertion*>* tokens=NULL,
-            const vector<Attribute*>* attributes=NULL
+            const saml2md::EntityDescriptor* issuer=nullptr,
+            const XMLCh* protocol=nullptr,
+            const saml2::NameID* nameid=nullptr,
+            const XMLCh* authn_instant=nullptr,
+            const XMLCh* session_index=nullptr,
+            const XMLCh* authncontext_class=nullptr,
+            const XMLCh* authncontext_decl=nullptr,
+            const vector<const Assertion*>* tokens=nullptr,
+            const vector<Attribute*>* attributes=nullptr
             );
         vector<string>::size_type logout(
             const Application& application,
@@ -102,7 +112,7 @@ namespace shibsp {
             const set<string>* indexes
             );
 #endif
-        Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
+        Session* find(const Application& application, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
         void remove(const Application& application, const char* key);
         void test();
 
@@ -112,19 +122,51 @@ namespace shibsp {
             return (session_id ? session_id : "");
         }
 
-        Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
+        Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
             string id = active(application, request);
             if (!id.empty())
                 return find(application, id.c_str(), client_addr, timeout);
-            return NULL;
+            return nullptr;
         }
 
-        void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
+        Session* find(const Application& application, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
+            string id = active(application, request);
+            if (id.empty())
+                return nullptr;
+            try {
+                Session* session = find(application, id.c_str(), client_addr, timeout);
+                if (session)
+                    return session;
+                HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
+                if (response) {
+                    pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
+                    string exp(shib_cookie.second);
+                    exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+                    response->setCookie(shib_cookie.first.c_str(), exp.c_str());
+                }
+            }
+            catch (exception&) {
+                HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
+                if (response) {
+                    pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
+                    string exp(shib_cookie.second);
+                    exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+                    response->setCookie(shib_cookie.first.c_str(), exp.c_str());
+                }
+                throw;
+            }
+            return nullptr;
+        }
+
+        void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=nullptr) {
             pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
             const char* session_id = request.getCookie(shib_cookie.first.c_str());
             if (session_id && *session_id) {
-                if (response)
-                    response->setCookie(shib_cookie.first.c_str(), shib_cookie.second);
+                if (response) {
+                    string exp(shib_cookie.second);
+                    exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
+                    response->setCookie(shib_cookie.first.c_str(), exp.c_str());
+                }
                 remove(application, session_id);
             }
         }
@@ -136,6 +178,7 @@ namespace shibsp {
         unsigned long m_cacheTimeout;
 #ifndef SHIBSP_LITE
         StorageService* m_storage;
+        StorageService* m_storage_lite;
 #endif
 
     private:
@@ -143,15 +186,16 @@ namespace shibsp {
         // maintain back-mappings of NameID/SessionIndex -> session key
         void insert(const char* key, time_t expires, const char* name, const char* index);
         bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
-#endif
 
+        bool m_cacheAssertions;
+#endif
         const DOMElement* m_root;         // Only valid during initialization
         unsigned long m_inprocTimeout;
 
         // inproc means we buffer sessions in memory
         RWLock* m_lock;
         map<string,StoredSession*> m_hashtable;
-    
+
         // management of buffered sessions
         void dormant(const char* key);
         static void* cleanup_fn(void*);
@@ -165,9 +209,9 @@ namespace shibsp {
     public:
         StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
 #ifndef SHIBSP_LITE
-                m_nameid(NULL),
+                m_nameid(nullptr),
 #endif
-                m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
+                m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
             auto_ptr_XMLCh exp(m_obj["expires"].string());
             if (exp.get()) {
                 DateTime iso(exp.get());
@@ -180,18 +224,18 @@ namespace shibsp {
             if (nameid) {
                 // Parse and bind the document into an XMLObject.
                 istringstream instr(nameid);
-                DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); 
+                DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
                 XercesJanitor<DOMDocument> janitor(doc);
                 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
                 n->unmarshall(doc->getDocumentElement(), true);
                 janitor.release();
                 m_nameid = n.release();
             }
-#endif            
+#endif
             if (cache->inproc)
                 m_lock = Mutex::create();
         }
-        
+
         ~StoredSession() {
             delete m_lock;
             m_obj.destroy();
@@ -201,7 +245,7 @@ namespace shibsp {
             for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
 #endif
         }
-        
+
         Lockable* lock() {
             if (m_lock)
                 m_lock->lock();
@@ -274,7 +318,7 @@ namespace shibsp {
             }
             return m_ids;
         }
-        
+
         void validate(const Application& application, const char* client_addr, time_t* timeout);
 
 #ifndef SHIBSP_LITE
@@ -302,18 +346,31 @@ namespace shibsp {
         time_t m_expires,m_lastAccess;
         Mutex* m_lock;
     };
-    
+
     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
     {
         return new SSCache(e);
     }
 }
 
+Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
+{
+    return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
+}
+
 void SHIBSP_API shibsp::registerSessionCaches()
 {
     SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
 }
 
+Session::Session()
+{
+}
+
+Session::~Session()
+{
+}
+
 void StoredSession::unmarshallAttributes() const
 {
     Attribute* attribute;
@@ -337,7 +394,7 @@ void StoredSession::unmarshallAttributes() const
 
 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
 {
-    time_t now = time(NULL);
+    time_t now = time(nullptr);
 
     // Basic expiration?
     if (m_expires > 0) {
@@ -362,7 +419,7 @@ void StoredSession::validate(const Application& application, const char* client_
 
     if (!timeout)
         return;
-    
+
     if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
         DDFJanitor jin(in);
@@ -370,7 +427,7 @@ void StoredSession::validate(const Application& application, const char* client_
         in.addmember("key").string(getID());
         in.addmember("version").integer(m_obj["version"].integer());
         if (*timeout) {
-            // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  
+            // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
 #ifndef HAVE_GMTIME_R
             struct tm* ptime=gmtime(timeout);
 #else
@@ -420,7 +477,7 @@ void StoredSession::validate(const Application& application, const char* client_
         if (*timeout > 0 && now - lastAccess >= *timeout) {
             m_cache->m_log.info("session timed out (ID: %s)", getID());
             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
-        } 
+        }
 
         // Update storage expiration, if possible.
         try {
@@ -429,7 +486,7 @@ void StoredSession::validate(const Application& application, const char* client_
         catch (exception& ex) {
             m_cache->m_log.error("failed to update session expiration: %s", ex.what());
         }
-            
+
         if (ver > curver) {
             // We got an updated record back.
             DDF newobj;
@@ -462,7 +519,7 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
         throw ConfigurationException("Session modification requires a StorageService.");
 
     m_cache->m_log.debug("adding attributes to session (%s)", getID());
-    
+
     int ver;
     do {
         DDF attr;
@@ -473,13 +530,13 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
             attr = (*a)->marshall();
             attrs.add(attr);
         }
-        
+
         // Tentatively increment the version.
         m_obj["version"].integer(m_obj["version"].integer()+1);
-        
+
         ostringstream str;
         str << m_obj;
-        string record(str.str()); 
+        string record(str.str());
 
         try {
             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
@@ -489,7 +546,7 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
             m_obj["version"].integer(m_obj["version"].integer()-1);
             vector<Attribute*>::size_type count = attributes.size();
             while (count--)
-                attrs.last().destroy();            
+                attrs.last().destroy();
             throw;
         }
 
@@ -498,7 +555,7 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
             m_obj["version"].integer(m_obj["version"].integer()-1);
             vector<Attribute*>::size_type count = attributes.size();
             while (count--)
-                attrs.last().destroy();            
+                attrs.last().destroy();
         }
         if (!ver) {
             // Fatal problem with update.
@@ -507,12 +564,12 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
         else if (ver < 0) {
             // Out of sync.
             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
-            ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
+            ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
             if (!ver) {
                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
                 throw IOException("Unable to read back stored session.");
             }
-            
+
             // Reset object.
             DDF newobj;
             istringstream in(record);
@@ -554,18 +611,18 @@ const Assertion* StoredSession::getAssertion(const char* id) const
     map<string,Assertion*>::const_iterator i = m_tokens.find(id);
     if (i!=m_tokens.end())
         return i->second;
-    
+
     string tokenstr;
-    if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
+    if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
         throw FatalProfileException("Assertion not found in cache.");
 
     // Parse and bind the document into an XMLObject.
     istringstream instr(tokenstr);
-    DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); 
+    DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
     XercesJanitor<DOMDocument> janitor(doc);
     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
     janitor.release();
-    
+
     Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
     if (!token)
         throw FatalProfileException("Request for cached assertion returned an unknown object type.");
@@ -593,25 +650,25 @@ void StoredSession::addAssertion(Assertion* assertion)
     m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
 
     time_t exp;
-    if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
+    if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
         throw IOException("Unable to load expiration time for stored session.");
 
     ostringstream tokenstr;
     tokenstr << *assertion;
     if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
         throw IOException("Attempted to insert duplicate assertion ID into session.");
-    
+
     int ver;
     do {
-        DDF token = DDF(NULL).string(id.get());
+        DDF token = DDF(nullptr).string(id.get());
         m_obj["assertions"].add(token);
 
         // Tentatively increment the version.
         m_obj["version"].integer(m_obj["version"].integer()+1);
-    
+
         ostringstream str;
         str << m_obj;
-        string record(str.str()); 
+        string record(str.str());
 
         try {
             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
@@ -626,7 +683,7 @@ void StoredSession::addAssertion(Assertion* assertion)
         if (ver <= 0) {
             token.destroy();
             m_obj["version"].integer(m_obj["version"].integer()-1);
-        }            
+        }
         if (!ver) {
             // Fatal problem with update.
             m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
@@ -636,13 +693,13 @@ void StoredSession::addAssertion(Assertion* assertion)
         else if (ver < 0) {
             // Out of sync.
             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
-            ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
+            ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
             if (!ver) {
                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
                 m_cache->m_storage->deleteText(getID(), id.get());
                 throw IOException("Unable to read back stored session.");
             }
-            
+
             // Reset object.
             DDF newobj;
             istringstream in(record);
@@ -655,7 +712,7 @@ void StoredSession::addAssertion(Assertion* assertion)
             newobj["version"].integer(ver);
             m_obj.destroy();
             m_obj = newobj;
-            
+
             ver = -1;
         }
     } while (ver < 0); // negative indicates a sync issue so we retry
@@ -673,29 +730,47 @@ void StoredSession::addAssertion(Assertion* assertion)
 
 #endif
 
+SessionCache::SessionCache()
+{
+}
+
+SessionCache::~SessionCache()
+{
+}
+
+SessionCacheEx::SessionCacheEx()
+{
+}
+
+SessionCacheEx::~SessionCacheEx()
+{
+}
+
 SSCache::SSCache(const DOMElement* e)
-    : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(3600),
+    : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(28800),
 #ifndef SHIBSP_LITE
-        m_storage(NULL),
+      m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
 #endif
-        m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
+      m_root(e), m_inprocTimeout(900), m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
 {
+    static const XMLCh cacheAssertions[] =  UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
     static const XMLCh cacheTimeout[] =     UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
     static const XMLCh inprocTimeout[] =    UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
     static const XMLCh _StorageService[] =  UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
+    static const XMLCh _StorageServiceLite[] = UNICODE_LITERAL_18(S,t,o,r,a,g,e,S,e,r,v,i,c,e,L,i,t,e);
 
     SPConfig& conf = SPConfig::getConfig();
     inproc = conf.isEnabled(SPConfig::InProcess);
 
     if (e) {
-        const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
+        const XMLCh* tag=e->getAttributeNS(nullptr,cacheTimeout);
         if (tag && *tag) {
             m_cacheTimeout = XMLString::parseInt(tag);
             if (!m_cacheTimeout)
-                m_cacheTimeout=3600;
+                m_cacheTimeout=28800;
         }
         if (inproc) {
-            const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
+            const XMLCh* tag=e->getAttributeNS(nullptr,inprocTimeout);
             if (tag && *tag) {
                 m_inprocTimeout = XMLString::parseInt(tag);
                 if (!m_inprocTimeout)
@@ -706,7 +781,7 @@ SSCache::SSCache(const DOMElement* e)
 
 #ifndef SHIBSP_LITE
     if (conf.isEnabled(SPConfig::OutOfProcess)) {
-        const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
+        const XMLCh* tag = e ? e->getAttributeNS(nullptr,_StorageService) : nullptr;
         if (tag && *tag) {
             auto_ptr_char ssid(tag);
             m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
@@ -715,6 +790,21 @@ SSCache::SSCache(const DOMElement* e)
         }
         if (!m_storage)
             throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
+
+        tag = e ? e->getAttributeNS(nullptr,_StorageServiceLite) : nullptr;
+        if (tag && *tag) {
+            auto_ptr_char ssid(tag);
+            m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
+            if (m_storage_lite)
+                m_log.info("bound to StorageServiceLite (%s)", ssid.get());
+        }
+        if (!m_storage_lite) {
+            m_log.info("No StorageServiceLite specified. Using standard StorageService.");
+            m_storage_lite = m_storage;
+        }
+        tag = e ? e->getAttributeNS(nullptr, cacheAssertions) : nullptr;
+        if (tag && (*tag == chLatin_f || *tag == chDigit_0))
+            m_cacheAssertions = false;
     }
 #endif
 
@@ -746,7 +836,7 @@ SSCache::~SSCache()
         // Shut down the cleanup thread and let it know...
         shutdown = true;
         shutdown_wait->signal();
-        cleanup_thread->join(NULL);
+        cleanup_thread->join(nullptr);
 
         for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
         delete m_lock;
@@ -770,7 +860,7 @@ SSCache::~SSCache()
 void SSCache::test()
 {
     auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
-    m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
+    m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
     m_storage->deleteString("SessionCacheTest", temp.get());
 }
 
@@ -788,7 +878,7 @@ void SSCache::insert(const char* key, time_t expires, const char* name, const ch
     // Since we can't guarantee uniqueness, check for an existing record.
     string record;
     time_t recordexp;
-    int ver = m_storage->readText("NameID", name, &record, &recordexp);
+    int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
     if (ver > 0) {
         // Existing record, so we need to unmarshall it.
         istringstream in(record);
@@ -796,7 +886,7 @@ void SSCache::insert(const char* key, time_t expires, const char* name, const ch
     }
     else {
         // New record.
-        obj.structure();
+        obj = DDF(nullptr).structure();
     }
 
     if (!index || !*index)
@@ -804,7 +894,7 @@ void SSCache::insert(const char* key, time_t expires, const char* name, const ch
     DDF sessions = obj.addmember(index);
     if (!sessions.islist())
         sessions.list();
-    DDF session = DDF(NULL).string(key);
+    DDF session = DDF(nullptr).string(key);
     sessions.add(session);
 
     // Remarshall the record.
@@ -813,13 +903,13 @@ void SSCache::insert(const char* key, time_t expires, const char* name, const ch
 
     // Try and store it back...
     if (ver > 0) {
-        ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
+        ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
         if (ver <= 0) {
             // Out of sync, or went missing, so retry.
             return insert(key, expires, name, index);
         }
     }
-    else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
+    else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
         // Hit a dup, so just retry, hopefully hitting the other branch.
         return insert(key, expires, name, index);
     }
@@ -849,17 +939,17 @@ void SSCache::insert(
 
     m_log.debug("creating new session");
 
-    time_t now = time(NULL);
+    time_t now = time(nullptr);
     auto_ptr_char index(session_index);
-    auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
-    auto_ptr_char name(nameid ? nameid->getName() : NULL);
+    auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
+    auto_ptr_char name(nameid ? nameid->getName() : nullptr);
 
     if (nameid) {
         // Check for a pending logout.
         if (strlen(name.get()) > 255)
             const_cast<char*>(name.get())[255] = 0;
         string pending;
-        int ver = m_storage->readText("Logout", name.get(), &pending);
+        int ver = m_storage_lite->readText("Logout", name.get(), &pending);
         if (ver > 0) {
             DDF pendobj;
             DDFJanitor jpend(pendobj);
@@ -868,7 +958,7 @@ void SSCache::insert(
             // IdP.SP.index contains logout expiration, if any.
             DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
             const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
-            if (!logexpstr && session_index)    // we tried an exact session match, now try for NULL
+            if (!logexpstr && session_index)    // we tried an exact session match, now try for nullptr
                 logexpstr = deadmenwalking["_shibnull"].string();
             if (logexpstr) {
                 auto_ptr_XMLCh dt(logexpstr);
@@ -885,6 +975,7 @@ void SSCache::insert(
 
     // Store session properties in DDF.
     DDF obj = DDF(key.get()).structure();
+    DDFJanitor entryobj(obj);
     obj.addmember("version").integer(1);
     obj.addmember("application_id").string(application.getId());
 
@@ -927,15 +1018,15 @@ void SSCache::insert(
         obj.addmember("nameid").string(namestr.str().c_str());
     }
 
-    if (tokens) {
+    if (tokens && m_cacheAssertions) {
         obj.addmember("assertions").list();
         for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
             auto_ptr_char tokenid((*t)->getID());
-            DDF tokid = DDF(NULL).string(tokenid.get());
+            DDF tokid = DDF(nullptr).string(tokenid.get());
             obj["assertions"].add(tokid);
         }
     }
-    
+
     if (attributes) {
         DDF attr;
         DDF attrlist = obj.addmember("attributes").list();
@@ -944,14 +1035,14 @@ void SSCache::insert(
             attrlist.add(attr);
         }
     }
-    
+
     ostringstream record;
     record << obj;
-    
+
     m_log.debug("storing new session...");
     if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
         throw FatalProfileException("Attempted to create a session with a duplicate key.");
-    
+
     // Store the reverse mapping for logout.
     try {
         if (nameid)
@@ -961,7 +1052,7 @@ void SSCache::insert(
         m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
     }
 
-    if (tokens) {
+    if (tokens && m_cacheAssertions) {
         try {
             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
                 ostringstream tokenstr;
@@ -977,9 +1068,20 @@ void SSCache::insert(
     }
 
     const char* pid = obj["entity_id"].string();
-    m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", httpRequest.getRemoteAddr().c_str());
+    const char* prot = obj["protocol"].string();
+    m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
+        key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
 
     // Transaction Logging
+    string primaryAssertionID("none");
+    if (m_cacheAssertions) {
+        if (tokens)
+            primaryAssertionID = obj["assertions"].first().string();
+    }
+    else if (tokens) {
+        auto_ptr_char tokenid(tokens->front()->getID());
+        primaryAssertionID = tokenid.get();
+    }
     TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
     Locker locker(xlog);
     xlog->log.infoStream() <<
@@ -993,8 +1095,12 @@ void SSCache::insert(
             httpRequest.getRemoteAddr() <<
         ") with (NameIdentifier: " <<
             (nameid ? name.get() : "none") <<
+        ") using (Protocol: " <<
+            (prot ? prot : "none") <<
+        ") from (AssertionID: " <<
+            primaryAssertionID <<
         ")";
-    
+
     if (attributes) {
         xlog->log.infoStream() <<
             "Cached the following attributes with session (ID: " <<
@@ -1007,9 +1113,23 @@ void SSCache::insert(
         xlog->log.info("}");
     }
 
-    pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
+    time_t cookieLifetime = 0;
+    pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_", &cookieLifetime);
     string k(key.get());
     k += shib_cookie.second;
+
+    if (cookieLifetime > 0) {
+        cookieLifetime += now;
+#ifndef HAVE_GMTIME_R
+        ptime=gmtime(&cookieLifetime);
+#else
+        ptime=gmtime_r(&cookieLifetime,&res);
+#endif
+        char cookietimebuf[64];
+        strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
+        k += cookietimebuf;
+    }
+
     httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
 }
 
@@ -1021,7 +1141,7 @@ bool SSCache::matches(
     const set<string>* indexes
     )
 {
-    auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
+    auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
     try {
         Session* session = find(application, request);
         if (session) {
@@ -1054,7 +1174,7 @@ vector<string>::size_type SSCache::logout(
     if (!m_storage)
         throw ConfigurationException("SessionCache insertion requires a StorageService.");
 
-    auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
+    auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
     auto_ptr_char name(nameid.getName());
 
     m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
@@ -1080,13 +1200,13 @@ vector<string>::size_type SSCache::logout(
         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
 
         time_t oldexp = 0;
-        ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
+        ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
         if (ver > 0) {
             istringstream lin(record);
             lin >> obj;
         }
         else {
-            obj = DDF(NULL).structure();
+            obj = DDF(nullptr).structure();
         }
 
         // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
@@ -1104,13 +1224,13 @@ vector<string>::size_type SSCache::logout(
         lout << obj;
 
         if (ver > 0) {
-            ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
+            ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
             if (ver <= 0) {
                 // Out of sync, or went missing, so retry.
                 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
             }
         }
-        else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
+        else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
             // Hit a dup, so just retry, hopefully hitting the other branch.
             return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
         }
@@ -1120,7 +1240,7 @@ vector<string>::size_type SSCache::logout(
     }
 
     // Read in potentially matching sessions.
-    ver = m_storage->readText("NameID", name.get(), &record);
+    ver = m_storage_lite->readText("NameID", name.get(), &record);
     if (ver == 0) {
         m_log.debug("no active sessions to logout for supplied issuer and subject");
         return 0;
@@ -1137,7 +1257,7 @@ vector<string>::size_type SSCache::logout(
             key = sessions.first();
             while (key.isstring()) {
                 // Fetch the session for comparison.
-                Session* session = NULL;
+                Session* session = nullptr;
                 try {
                     session = find(application, key.string());
                 }
@@ -1176,19 +1296,19 @@ vector<string>::size_type SSCache::logout(
         }
         sessions = obj.next();
     }
-    
+
     if (obj.first().isnull())
         obj.destroy();
 
     // If possible, write back the mapping record (this isn't crucial).
     try {
         if (obj.isnull()) {
-            m_storage->deleteText("NameID", name.get());
+            m_storage_lite->deleteText("NameID", name.get());
         }
         else if (!sessionsKilled.empty()) {
             ostringstream out;
             out << obj;
-            if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
+            if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
                 m_log.warn("logout mapping record changed behind us, leaving it alone");
         }
     }
@@ -1203,7 +1323,7 @@ bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::Na
 {
     if (!XMLString::equals(n1.getName(), n2.getName()))
         return false;
-    
+
     const XMLCh* s1 = n1.getFormat();
     const XMLCh* s2 = n2.getFormat();
     if (!s1 || !*s1)
@@ -1212,7 +1332,7 @@ bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::Na
         s2 = saml2::NameID::UNSPECIFIED;
     if (!XMLString::equals(s1,s2))
         return false;
-    
+
     s1 = n1.getNameQualifier();
     s2 = n2.getNameQualifier();
     if (!s1 || !*s1)
@@ -1241,7 +1361,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
 #ifdef _DEBUG
     xmltooling::NDC ndc("find");
 #endif
-    StoredSession* session=NULL;
+    StoredSession* session=nullptr;
 
     if (inproc) {
         m_log.debug("searching local cache for session (%s)", key);
@@ -1269,7 +1389,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
             in.addmember("key").string(key);
             in.addmember("application_id").string(application.getId());
             if (timeout && *timeout) {
-                // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  
+                // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
 #ifndef HAVE_GMTIME_R
                 struct tm* ptime=gmtime(timeout);
 #else
@@ -1280,19 +1400,19 @@ Session* SSCache::find(const Application& application, const char* key, const ch
                 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
                 in.addmember("timeout").string(timebuf);
             }
-            
+
             try {
                 out=application.getServiceProvider().getListenerService()->send(in);
                 if (!out.isstruct()) {
                     out.destroy();
                     m_log.debug("session not found in remote cache");
-                    return NULL;
+                    return nullptr;
                 }
-                
+
                 // Wrap the results in a local entry and save it.
                 session = new StoredSession(this, out);
                 // The remote end has handled timeout issues, we handle address and expiration checks.
-                timeout = NULL;
+                timeout = nullptr;
             }
             catch (...) {
                 out.destroy();
@@ -1306,22 +1426,22 @@ Session* SSCache::find(const Application& application, const char* key, const ch
                 throw ConfigurationException("SessionCache lookup requires a StorageService.");
 
             m_log.debug("searching for session (%s)", key);
-            
+
             DDF obj;
             time_t lastAccess;
             string record;
             int ver = m_storage->readText(key, "session", &record, &lastAccess);
             if (!ver)
-                return NULL;
-            
+                return nullptr;
+
             m_log.debug("reconstituting session and checking validity");
-            
+
             istringstream in(record);
             in >> obj;
-            
+
             lastAccess -= m_cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched
-            time_t now=time(NULL);
-            
+            time_t now=time(nullptr);
+
             if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
                 m_log.info("session timed out (ID: %s)", key);
                 remove(application, key);
@@ -1334,7 +1454,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
                 obj.destroy();
                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
             }
-            
+
             if (timeout) {
                 // Update storage expiration, if possible.
                 try {
@@ -1348,7 +1468,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
             // Wrap the results in a local entry and save it.
             session = new StoredSession(this, obj);
             // We handled timeout issues, still need to handle address and expiration checks.
-            timeout = NULL;
+            timeout = nullptr;
 #else
             throw ConfigurationException("SessionCache search requires a StorageService.");
 #endif
@@ -1374,7 +1494,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
     if (!XMLString::equals(session->getApplicationID(), application.getId())) {
         m_log.error("an application (%s) tried to access another application's session", application.getId());
         session->unlock();
-        return NULL;
+        return nullptr;
     }
 
     // Verify currency and update the timestamp if indicated by caller.
@@ -1386,7 +1506,7 @@ Session* SSCache::find(const Application& application, const char* key, const ch
         remove(application, key);
         throw;
     }
-    
+
     return session;
 }
 
@@ -1398,7 +1518,7 @@ void SSCache::remove(const Application& application, const char* key)
     // Take care of local copy.
     if (inproc)
         dormant(key);
-    
+
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         // Remove the session from storage directly.
 #ifndef SHIBSP_LITE
@@ -1419,7 +1539,7 @@ void SSCache::remove(const Application& application, const char* key)
         in.structure();
         in.addmember("key").string(key);
         in.addmember("application_id").string(application.getId());
-        
+
         DDF out = application.getServiceProvider().getListenerService()->send(in);
         out.destroy();
     }
@@ -1447,7 +1567,7 @@ void SSCache::dormant(const char* key)
     StoredSession* entry=i->second;
     m_hashtable.erase(key);
     entry->lock();
-    
+
     // unlock the cache
     m_lock->unlock();
 
@@ -1464,15 +1584,16 @@ void SSCache::cleanup()
 #endif
 
     Mutex* mutex = Mutex::create();
-  
+
     // Load our configuration details...
     static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
-    const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
+    const XMLCh* tag=m_root ? m_root->getAttributeNS(nullptr,cleanupInterval) : nullptr;
     int rerun_timer = 900;
-    if (tag && *tag)
+    if (tag && *tag) {
         rerun_timer = XMLString::parseInt(tag);
-    if (rerun_timer <= 0)
-        rerun_timer = 900;
+        if (rerun_timer <= 0)
+            rerun_timer = 900;
+    }
 
     mutex->lock();
 
@@ -1488,12 +1609,12 @@ void SSCache::cleanup()
         // first pass is done holding a read-lock while we iterate over
         // the cache.  The second pass doesn't need a lock because
         // the 'deletes' will lock the cache.
-    
+
         // Pass 1: iterate over the map and find all entries that have not been
         // used in the allotted timeout.
         vector<string> stale_keys;
-        time_t stale = time(NULL) - m_inprocTimeout;
-    
+        time_t stale = time(nullptr) - m_inprocTimeout;
+
         m_log.debug("cleanup thread running");
 
         m_lock->rdlock();
@@ -1506,10 +1627,10 @@ void SSCache::cleanup()
                 stale_keys.push_back(i->first);
         }
         m_lock->unlock();
-    
+
         if (!stale_keys.empty()) {
             m_log.info("purging %d old sessions", stale_keys.size());
-    
+
             // Pass 2: walk through the list of stale entries and remove them from the cache
             for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
                 dormant(j->c_str());
@@ -1522,19 +1643,19 @@ void SSCache::cleanup()
 
     mutex->unlock();
     delete mutex;
-    Thread::exit(NULL);
+    Thread::exit(nullptr);
 }
 
 void* SSCache::cleanup_fn(void* cache_p)
 {
 #ifndef WIN32
-    // First, let's block all signals 
+    // First, let's block all signals
     Thread::mask_all_signals();
 #endif
 
     // Now run the cleanup process.
     reinterpret_cast<SSCache*>(cache_p)->cleanup();
-    return NULL;
+    return nullptr;
 }
 
 #ifndef SHIBSP_LITE
@@ -1558,7 +1679,7 @@ void SSCache::receive(DDF& in, ostream& out)
         string record;
         time_t lastAccess;
         if (!m_storage->readText(key, "session", &record, &lastAccess)) {
-            DDF ret(NULL);
+            DDF ret(nullptr);
             DDFJanitor jan(ret);
             out << ret;
             return;
@@ -1566,7 +1687,7 @@ void SSCache::receive(DDF& in, ostream& out)
 
         // Adjust for expiration to recover last access time and check timeout.
         lastAccess -= m_cacheTimeout;
-        time_t now=time(NULL);
+        time_t now=time(nullptr);
 
         // See if we need to check for a timeout.
         if (in["timeout"].string()) {
@@ -1575,12 +1696,12 @@ void SSCache::receive(DDF& in, ostream& out)
             DateTime dtobj(dt.get());
             dtobj.parseDateTime();
             timeout = dtobj.getEpoch();
-                    
+
             if (timeout > 0 && now - lastAccess >= timeout) {
                 m_log.info("session timed out (ID: %s)", key);
                 remove(*app, key);
                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
-            } 
+            }
 
             // Update storage expiration, if possible.
             try {
@@ -1590,7 +1711,7 @@ void SSCache::receive(DDF& in, ostream& out)
                 m_log.error("failed to update session expiration: %s", ex.what());
             }
         }
-            
+
         // Send the record back.
         out << record;
     }
@@ -1611,7 +1732,7 @@ void SSCache::receive(DDF& in, ostream& out)
 
         // Adjust for expiration to recover last access time and check timeout.
         lastAccess -= m_cacheTimeout;
-        time_t now=time(NULL);
+        time_t now=time(nullptr);
 
         // See if we need to check for a timeout.
         time_t timeout = 0;
@@ -1621,11 +1742,11 @@ void SSCache::receive(DDF& in, ostream& out)
             dtobj.parseDateTime();
             timeout = dtobj.getEpoch();
         }
-                
+
         if (timeout > 0 && now - lastAccess >= timeout) {
             m_log.info("session timed out (ID: %s)", key);
             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
-        } 
+        }
 
         // Update storage expiration, if possible.
         try {
@@ -1634,13 +1755,13 @@ void SSCache::receive(DDF& in, ostream& out)
         catch (exception& ex) {
             m_log.error("failed to update session expiration: %s", ex.what());
         }
-            
+
         if (ver > curver) {
             // Send the record back.
             out << record;
         }
         else {
-            DDF ret(NULL);
+            DDF ret(nullptr);
             DDFJanitor jan(ret);
             out << ret;
         }
@@ -1655,7 +1776,7 @@ void SSCache::receive(DDF& in, ostream& out)
             throw ConfigurationException("Application not found, check configuration?");
 
         remove(*app, key);
-        DDF ret(NULL);
+        DDF ret(nullptr);
         DDFJanitor jan(ret);
         out << ret;
     }