First set of logout base classes and non-building draft of SP-initiated logout.
[shibboleth/sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
index 0ed3e73..c607c39 100644 (file)
@@ -1,5 +1,5 @@
 /*\r
- *  Copyright 2001-2005 Internet2\r
+ *  Copyright 2001-2007 Internet2\r
  * \r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
  * limitations under the License.\r
  */\r
 \r
-/** StorageServiceSessionCache.cpp\r
+/**\r
+ * StorageServiceSessionCache.cpp\r
  * \r
- * StorageService-based SessionCache implementation\r
+ * StorageService-based SessionCache implementation.\r
+ * \r
+ * Instead of optimizing this plugin with a buffering scheme that keeps objects around\r
+ * and avoids extra parsing steps, I'm assuming that systems that require such can\r
+ * layer their own cache plugin on top of this version either by delegating to it\r
+ * or using the remoting support. So this version will load sessions directly\r
+ * from the StorageService, instantiate enough to expose the Session API,\r
+ * and then delete everything when they're unlocked. All data in memory is always\r
+ * kept in sync with the StorageService (no lazy updates).\r
  */\r
 \r
 #include "internal.h"\r
@@ -49,7 +58,19 @@ namespace shibsp {
     class StoredSession : public virtual Session\r
     {\r
     public:\r
-        StoredSession(SSCache* cache, DDF& obj) : m_cache(cache), m_obj(obj) {}\r
+        StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {\r
+            const char* nameid = obj["nameid"].string();\r
+            if (nameid) {\r
+                // Parse and bind the document into an XMLObject.\r
+                istringstream instr(nameid);\r
+                DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
+                XercesJanitor<DOMDocument> janitor(doc);\r
+                auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());\r
+                n->unmarshall(doc->getDocumentElement(), true);\r
+                janitor.release();\r
+                m_nameid = n.release();\r
+            }\r
+        }\r
         \r
         ~StoredSession();\r
         \r
@@ -60,17 +81,23 @@ namespace shibsp {
             delete this;\r
         }\r
         \r
+        const char* getID() const {\r
+            return m_obj.name();\r
+        }\r
         const char* getClientAddress() const {\r
-            return m_obj["client_address"].string();\r
+            return m_obj["client_addr"].string();\r
         }\r
         const char* getEntityID() const {\r
             return m_obj["entity_id"].string();\r
         }\r
+        const char* getProtocol() const {\r
+            return m_obj["protocol"].string();\r
+        }\r
         const char* getAuthnInstant() const {\r
             return m_obj["authn_instant"].string();\r
         }\r
-        const opensaml::saml2::NameID& getNameID() const {\r
-            return *m_nameid;\r
+        const opensaml::saml2::NameID* getNameID() const {\r
+            return m_nameid;\r
         }\r
         const char* getSessionIndex() const {\r
             return m_obj["session_index"].string();\r
@@ -81,59 +108,78 @@ namespace shibsp {
         const char* getAuthnContextDeclRef() const {\r
             return m_obj["authncontext_decl"].string();\r
         }\r
-        const vector<const Attribute*>& getAttributes() const {\r
+        const multimap<string,Attribute*>& getAttributes() const {\r
+            if (m_attributes.empty())\r
+                unmarshallAttributes();\r
             return m_attributes;\r
         }\r
         const vector<const char*>& getAssertionIDs() const {\r
             if (m_ids.empty()) {\r
-                DDF id = m_obj["assertion_ids"].first();\r
+                DDF ids = m_obj["assertions"];\r
+                DDF id = ids.first();\r
                 while (id.isstring()) {\r
                     m_ids.push_back(id.string());\r
-                    id = id.next();\r
+                    id = ids.next();\r
                 }\r
             }\r
             return m_ids;\r
         }\r
         \r
         void addAttributes(const vector<Attribute*>& attributes);\r
-        const RootObject* getAssertion(const char* id) const;\r
-        void addAssertion(RootObject* assertion);\r
+        const Assertion* getAssertion(const char* id) const;\r
+        void addAssertion(Assertion* assertion);\r
 \r
     private:\r
+        void unmarshallAttributes() const;\r
+\r
         DDF m_obj;\r
         saml2::NameID* m_nameid;\r
-        vector<const Attribute*> m_attributes;\r
+        mutable multimap<string,Attribute*> m_attributes;\r
         mutable vector<const char*> m_ids;\r
-        mutable map<string,RootObject*> m_tokens;\r
-        time_t m_sessionCreated,m_lastAccess;\r
+        mutable map<string,Assertion*> m_tokens;\r
         SSCache* m_cache;\r
     };\r
     \r
-    class SSCache : public SessionCache\r
+    class SSCache : public SessionCache, public virtual Remoted\r
     {\r
     public:\r
         SSCache(const DOMElement* e);\r
-        ~SSCache() {}\r
+        ~SSCache();\r
     \r
-        DDF receive(const DDF& in);\r
+        void receive(DDF& in, ostream& out);\r
         \r
         string insert(\r
+            time_t expires,\r
             const Application& application,\r
-            const char* client_addr,\r
+            const char* client_addr=NULL,\r
+            const saml2md::EntityDescriptor* issuer=NULL,\r
+            const XMLCh* protocol=NULL,\r
+            const saml2::NameID* nameid=NULL,\r
+            const XMLCh* authn_instant=NULL,\r
+            const XMLCh* session_index=NULL,\r
+            const XMLCh* authncontext_class=NULL,\r
+            const XMLCh* authncontext_decl=NULL,\r
+            const vector<const Assertion*>* tokens=NULL,\r
+            const multimap<string,Attribute*>* attributes=NULL\r
+            );\r
+        Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);\r
+        void remove(const char* key, const Application& application);\r
+        void remove(\r
             const saml2md::EntityDescriptor* issuer,\r
             const saml2::NameID& nameid,\r
-            const char* authn_instant=NULL,\r
-            const char* session_index=NULL,\r
-            const char* authncontext_class=NULL,\r
-            const char* authncontext_decl=NULL,\r
-            const RootObject* ssoToken=NULL,\r
-            const vector<Attribute*>* attributes=NULL\r
+            const char* index,\r
+            const Application& application,\r
+            vector<string>& sessions\r
             );\r
-        Session* find(const char* key, const Application& application, const char* client_addr);\r
-        void remove(const char* key, const Application& application, const char* client_addr);\r
 \r
         Category& m_log;\r
         StorageService* m_storage;\r
+\r
+    private:\r
+        // maintain back-mappings of NameID/SessionIndex -> session key\r
+        void insert(const char* key, time_t expires, const char* name, const char* index);\r
+\r
+        bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;\r
     };\r
 \r
     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)\r
@@ -141,15 +187,36 @@ namespace shibsp {
         return new SSCache(e);\r
     }\r
 \r
-    static const XMLCh storageService[] =   UNICODE_LITERAL_14(s,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
+    static const XMLCh _StorageService[] =   UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
 }\r
 \r
 StoredSession::~StoredSession()\r
 {\r
     m_obj.destroy();\r
     delete m_nameid;\r
-    for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());\r
-    for_each(m_tokens.begin(), m_tokens.end(), xmltooling::cleanup_pair<string,RootObject>());\r
+    for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());\r
+    for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());\r
+}\r
+\r
+void StoredSession::unmarshallAttributes() const\r
+{\r
+    Attribute* attribute;\r
+    DDF attrs = m_obj["attributes"];\r
+    DDF attr = attrs.first();\r
+    while (!attr.isnull()) {\r
+        try {\r
+            attribute = Attribute::unmarshall(attr);\r
+            m_attributes.insert(make_pair(attribute->getId(), attribute));\r
+            if (m_cache->m_log.isDebugEnabled())\r
+                m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",\r
+                    attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");\r
+        }\r
+        catch (AttributeException& ex) {\r
+            const char* id = attr.first().name();\r
+            m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());\r
+        }\r
+        attr = attrs.next();\r
+    }\r
 }\r
 \r
 void StoredSession::addAttributes(const vector<Attribute*>& attributes)\r
@@ -158,63 +225,109 @@ void StoredSession::addAttributes(const vector<Attribute*>& attributes)
     xmltooling::NDC ndc("addAttributes");\r
 #endif\r
 \r
-    m_cache->m_log.debug("adding attributes to session (%s)", m_obj.name());\r
-\r
-    DDF attr;\r
-    DDF attrs = m_obj["attributes"];\r
-    if (!attrs.islist())\r
-        attrs = m_obj.addmember("attributes").list();\r
-    for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {\r
-        attr = (*a)->marshall();\r
-        attrs.add(attr);\r
-    }\r
-    \r
-    ostringstream record;\r
-    record << m_obj;\r
+    m_cache->m_log.debug("adding attributes to session (%s)", getID());\r
     \r
-    if (!m_cache->m_storage->updateText(m_obj["application_id"].string(), m_obj.name(), record.str().c_str())) {\r
-        // Roll back modification to record.\r
-        vector<Attribute*>::size_type count = attributes.size();\r
-        while (count--)\r
-            attrs.last().destroy();            \r
-        m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());\r
-        throw IOException("Unable to update stored session.");\r
-    }\r
+    int ver;\r
+    do {\r
+        DDF attr;\r
+        DDF attrs = m_obj["attributes"];\r
+        if (!attrs.islist())\r
+            attrs = m_obj.addmember("attributes").list();\r
+        for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {\r
+            attr = (*a)->marshall();\r
+            attrs.add(attr);\r
+        }\r
+        \r
+        // Tentatively increment the version.\r
+        m_obj["version"].integer(m_obj["version"].integer()+1);\r
+        \r
+        ostringstream str;\r
+        str << m_obj;\r
+        string record(str.str()); \r
 \r
-    // Transfer ownership to us.\r
-    m_attributes.insert(m_attributes.end(), attributes.begin(), attributes.end());\r
+        try {\r
+            ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
+        }\r
+        catch (exception&) {\r
+            // Roll back modification to record.\r
+            m_obj["version"].integer(m_obj["version"].integer()-1);\r
+            vector<Attribute*>::size_type count = attributes.size();\r
+            while (count--)\r
+                attrs.last().destroy();            \r
+            throw;\r
+        }\r
+\r
+        if (ver <= 0) {\r
+            // Roll back modification to record.\r
+            m_obj["version"].integer(m_obj["version"].integer()-1);\r
+            vector<Attribute*>::size_type count = attributes.size();\r
+            while (count--)\r
+                attrs.last().destroy();            \r
+        }\r
+        if (!ver) {\r
+            // Fatal problem with update.\r
+            throw IOException("Unable to update stored session.");\r
+        }\r
+        else if (ver < 0) {\r
+            // Out of sync.\r
+            m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
+            ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
+            if (!ver) {\r
+                m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
+                throw IOException("Unable to read back stored session.");\r
+            }\r
+            \r
+            // Reset object.\r
+            DDF newobj;\r
+            istringstream in(record);\r
+            in >> newobj;\r
+\r
+            m_ids.clear();\r
+            for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
+            m_attributes.clear();\r
+            newobj["version"].integer(ver);\r
+            m_obj.destroy();\r
+            m_obj = newobj;\r
+\r
+            ver = -1;\r
+        }\r
+    } while (ver < 0);  // negative indicates a sync issue so we retry\r
 \r
     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
     Locker locker(xlog);\r
     xlog->log.infoStream() <<\r
         "Added the following attributes to session (ID: " <<\r
-            m_obj.name() <<\r
+            getID() <<\r
         ") for (applicationId: " <<\r
             m_obj["application_id"].string() <<\r
         ") {";\r
     for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)\r
         xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";\r
     xlog->log.info("}");\r
+\r
+    // We own them now, so clean them up.\r
+    for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());\r
 }\r
 \r
-const RootObject* StoredSession::getAssertion(const char* id) const\r
+const Assertion* StoredSession::getAssertion(const char* id) const\r
 {\r
-    map<string,RootObject*>::const_iterator i = m_tokens.find(id);\r
+    map<string,Assertion*>::const_iterator i = m_tokens.find(id);\r
     if (i!=m_tokens.end())\r
         return i->second;\r
     \r
-    // Parse and bind the document into an XMLObject.\r
-    const char* tokenstr = m_obj["assertions"][id].string();\r
-    if (!tokenstr)\r
+    string tokenstr;\r
+    if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))\r
         throw FatalProfileException("Assertion not found in cache.");\r
+\r
+    // Parse and bind the document into an XMLObject.\r
     istringstream instr(tokenstr);\r
     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
     XercesJanitor<DOMDocument> janitor(doc);\r
     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
     janitor.release();\r
     \r
-    RootObject* token = dynamic_cast<RootObject*>(xmlObject.get());\r
-    if (!token || !token->isAssertion())\r
+    Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());\r
+    if (!token)\r
         throw FatalProfileException("Request for cached assertion returned an unknown object type.");\r
 \r
     // Transfer ownership to us.\r
@@ -223,64 +336,199 @@ const RootObject* StoredSession::getAssertion(const char* id) const
     return token;\r
 }\r
 \r
-void StoredSession::addAssertion(RootObject* assertion)\r
+void StoredSession::addAssertion(Assertion* assertion)\r
 {\r
 #ifdef _DEBUG\r
     xmltooling::NDC ndc("addAssertion");\r
 #endif\r
     \r
-    if (!assertion || !assertion->isAssertion())\r
+    if (!assertion)\r
         throw FatalProfileException("Unknown object type passed to session for storage.");\r
 \r
     auto_ptr_char id(assertion->getID());\r
 \r
-    m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), m_obj.name());\r
+    m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());\r
+\r
+    time_t exp;\r
+    if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))\r
+        throw IOException("Unable to load expiration time for stored session.");\r
 \r
-    ostringstream os;\r
-    os << *assertion;\r
+    ostringstream tokenstr;\r
+    tokenstr << *assertion;\r
+    if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))\r
+        throw IOException("Attempted to insert duplicate assertion ID into session.");\r
     \r
-    DDF tokens = m_obj["assertions"];\r
-    if (!tokens.isstruct())\r
-        tokens = m_obj.addmember("assertions").structure();\r
-    tokens = tokens.addmember(id.get()).string(os.str().c_str());\r
+    int ver;\r
+    do {\r
+        DDF token = DDF(NULL).string(id.get());\r
+        m_obj["assertions"].add(token);\r
 \r
-    ostringstream record;\r
-    record << m_obj;\r
+        // Tentatively increment the version.\r
+        m_obj["version"].integer(m_obj["version"].integer()+1);\r
     \r
-    if (!m_cache->m_storage->updateText(m_obj["application_id"].string(), m_obj.name(), record.str().c_str())) {\r
-        // Roll back modification to record.\r
-        tokens.destroy();\r
-        m_cache->m_log.error("updateText failed on StorageService for session (%s)", m_obj.name());\r
-        throw IOException("Unable to update stored session.");\r
-    }\r
+        ostringstream str;\r
+        str << m_obj;\r
+        string record(str.str()); \r
+\r
+        try {\r
+            ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
+        }\r
+        catch (exception&) {\r
+            token.destroy();\r
+            m_obj["version"].integer(m_obj["version"].integer()-1);\r
+            m_cache->m_storage->deleteText(getID(), id.get());\r
+            throw;\r
+        }\r
+\r
+        if (ver <= 0) {\r
+            token.destroy();\r
+            m_obj["version"].integer(m_obj["version"].integer()-1);\r
+        }            \r
+        if (!ver) {\r
+            // Fatal problem with update.\r
+            m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());\r
+            m_cache->m_storage->deleteText(getID(), id.get());\r
+            throw IOException("Unable to update stored session.");\r
+        }\r
+        else if (ver < 0) {\r
+            // Out of sync.\r
+            m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
+            ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
+            if (!ver) {\r
+                m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
+                m_cache->m_storage->deleteText(getID(), id.get());\r
+                throw IOException("Unable to read back stored session.");\r
+            }\r
+            \r
+            // Reset object.\r
+            DDF newobj;\r
+            istringstream in(record);\r
+            in >> newobj;\r
+\r
+            m_ids.clear();\r
+            for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
+            m_attributes.clear();\r
+            newobj["version"].integer(ver);\r
+            m_obj.destroy();\r
+            m_obj = newobj;\r
+            \r
+            ver = -1;\r
+        }\r
+    } while (ver < 0); // negative indicates a sync issue so we retry\r
 \r
+    m_ids.clear();\r
     delete assertion;\r
 \r
     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
     Locker locker(xlog);\r
     xlog->log.info(\r
         "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",\r
-        id.get(), m_obj["application_id"].string(), m_obj.name()\r
+        id.get(), m_obj["application_id"].string(), getID()\r
         );\r
 }\r
 \r
 SSCache::SSCache(const DOMElement* e)\r
     : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)\r
 {\r
-    // TODO: assign storage service\r
+    SPConfig& conf = SPConfig::getConfig();\r
+    const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;\r
+    if (tag && *tag) {\r
+        auto_ptr_char ssid(tag);\r
+        m_storage = conf.getServiceProvider()->getStorageService(ssid.get());\r
+        if (m_storage)\r
+            m_log.info("bound to StorageService (%s)", ssid.get());\r
+        else\r
+            throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");\r
+    }\r
+\r
+    ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
+    if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
+        listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+    }\r
+    else {\r
+        m_log.info("no ListenerService available, cache remoting disabled");\r
+    }\r
+}\r
+\r
+SSCache::~SSCache()\r
+{\r
+    SPConfig& conf = SPConfig::getConfig();\r
+    ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
+    if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
+        listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+        listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
+    }\r
+}\r
+\r
+void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)\r
+{\r
+    string dup;\r
+    if (strlen(name) > 255) {\r
+        dup = string(name).substr(0,255);\r
+        name = dup.c_str();\r
+    }\r
+\r
+    DDF obj;\r
+    DDFJanitor jobj(obj);\r
+\r
+    // Since we can't guarantee uniqueness, check for an existing record.\r
+    string record;\r
+    time_t recordexp;\r
+    int ver = m_storage->readText("NameID", name, &record, &recordexp);\r
+    if (ver > 0) {\r
+        // Existing record, so we need to unmarshall it.\r
+        istringstream in(record);\r
+        in >> obj;\r
+    }\r
+    else {\r
+        // New record.\r
+        obj.structure();\r
+    }\r
+\r
+    if (!index || !*index)\r
+        index = "_shibnull";\r
+    DDF sessions = obj.addmember(index);\r
+    if (!sessions.islist())\r
+        sessions.list();\r
+    DDF session = DDF(NULL).string(key);\r
+    sessions.add(session);\r
+\r
+    // Remarshall the record.\r
+    ostringstream out;\r
+    out << obj;\r
+\r
+    // Try and store it back...\r
+    if (ver > 0) {\r
+        ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);\r
+        if (ver <= 0) {\r
+            // Out of sync, or went missing, so retry.\r
+            return insert(key, expires, name, index);\r
+        }\r
+    }\r
+    else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {\r
+        // Hit a dup, so just retry, hopefully hitting the other branch.\r
+        return insert(key, expires, name, index);\r
+    }\r
 }\r
 \r
 string SSCache::insert(\r
+    time_t expires,\r
     const Application& application,\r
     const char* client_addr,\r
     const saml2md::EntityDescriptor* issuer,\r
-    const saml2::NameID& nameid,\r
-    const char* authn_instant,\r
-    const char* session_index,\r
-    const char* authncontext_class,\r
-    const char* authncontext_decl,\r
-    const RootObject* ssoToken,\r
-    const vector<Attribute*>* attributes\r
+    const XMLCh* protocol,\r
+    const saml2::NameID* nameid,\r
+    const XMLCh* authn_instant,\r
+    const XMLCh* session_index,\r
+    const XMLCh* authncontext_class,\r
+    const XMLCh* authncontext_decl,\r
+    const vector<const Assertion*>* tokens,\r
+    const multimap<string,Attribute*>* attributes\r
     )\r
 {\r
 #ifdef _DEBUG\r
@@ -291,50 +539,68 @@ string SSCache::insert(
 \r
     auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());\r
 \r
-    time_t created = time(NULL);\r
+    // Store session properties in DDF.\r
+    DDF obj = DDF(key.get()).structure();\r
+    obj.addmember("version").integer(1);\r
+    obj.addmember("application_id").string(application.getId());\r
+\r
+    // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  \r
 #ifndef HAVE_GMTIME_R\r
-    struct tm* ptime=gmtime(&created);\r
+    struct tm* ptime=gmtime(&expires);\r
 #else\r
     struct tm res;\r
-    struct tm* ptime=gmtime_r(&created,&res);\r
+    struct tm* ptime=gmtime_r(&expires,&res);\r
 #endif\r
     char timebuf[32];\r
     strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
+    obj.addmember("expires").string(timebuf);\r
 \r
-    // Store session properties in DDF.\r
-    DDF obj = DDF(key.get()).structure();\r
-    obj.addmember("created").string(timebuf);\r
-    obj.addmember("client_address").string(client_addr);\r
-    obj.addmember("application_id").string(application.getId());\r
+    if (client_addr)\r
+        obj.addmember("client_addr").string(client_addr);\r
     if (issuer) {\r
         auto_ptr_char entity_id(issuer->getEntityID());\r
         obj.addmember("entity_id").string(entity_id.get());\r
     }\r
-    if (authn_instant)\r
-        obj.addmember("authn_instant").string(authn_instant);\r
+    if (protocol) {\r
+        auto_ptr_char prot(protocol);\r
+        obj.addmember("protocol").string(prot.get());\r
+    }\r
+    if (authn_instant) {\r
+        auto_ptr_char instant(authn_instant);\r
+        obj.addmember("authn_instant").string(instant.get());\r
+    }\r
+    auto_ptr_char index(session_index);\r
     if (session_index)\r
-        obj.addmember("session_index").string(session_index);\r
-    if (authncontext_class)\r
-        obj.addmember("authncontext_class").string(authncontext_class);\r
-    if (authncontext_decl)\r
-        obj.addmember("authncontext_decl").string(authncontext_decl);\r
-\r
-    ostringstream namestr;\r
-    namestr << nameid;\r
-    obj.addmember("nameid").string(namestr.str().c_str());\r
-    \r
-    if (ssoToken) {\r
-        ostringstream tokenstr;\r
-        tokenstr << *ssoToken;\r
-        auto_ptr_char tokenid(ssoToken->getID());\r
-        obj.addmember("assertions").structure().addmember(tokenid.get()).string(tokenstr.str().c_str());\r
+        obj.addmember("session_index").string(index.get());\r
+    if (authncontext_class) {\r
+        auto_ptr_char ac(authncontext_class);\r
+        obj.addmember("authncontext_class").string(ac.get());\r
+    }\r
+    if (authncontext_decl) {\r
+        auto_ptr_char ad(authncontext_decl);\r
+        obj.addmember("authncontext_decl").string(ad.get());\r
+    }\r
+\r
+    if (nameid) {\r
+        ostringstream namestr;\r
+        namestr << *nameid;\r
+        obj.addmember("nameid").string(namestr.str().c_str());\r
+    }\r
+\r
+    if (tokens) {\r
+        obj.addmember("assertions").list();\r
+        for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
+            auto_ptr_char tokenid((*t)->getID());\r
+            DDF tokid = DDF(NULL).string(tokenid.get());\r
+            obj["assertions"].add(tokid);\r
+        }\r
     }\r
     \r
     if (attributes) {\r
         DDF attr;\r
         DDF attrlist = obj.addmember("attributes").list();\r
-        for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {\r
-            attr = (*a)->marshall();\r
+        for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {\r
+            attr = a->second->marshall();\r
             attrlist.add(attr);\r
         }\r
     }\r
@@ -343,13 +609,40 @@ string SSCache::insert(
     record << obj;\r
     \r
     m_log.debug("storing new session...");\r
-    m_storage->createText(application.getId(), key.get(), record.str().c_str(), created + m_cacheTimeout);\r
+    time_t now = time(NULL);\r
+    if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))\r
+        throw FatalProfileException("Attempted to create a session with a duplicate key.");\r
+    \r
+    // Store the reverse mapping for logout.\r
+    auto_ptr_char name(nameid ? nameid->getName() : NULL);\r
+    try {\r
+        if (name.get())\r
+            insert(key.get(), expires, name.get(), index.get());\r
+    }\r
+    catch (exception& ex) {\r
+        m_log.error("error storing back mapping of NameID for logout: %s", ex.what());\r
+    }\r
+\r
+    if (tokens) {\r
+        try {\r
+            for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
+                ostringstream tokenstr;\r
+                tokenstr << *(*t);\r
+                auto_ptr_char tokenid((*t)->getID());\r
+                if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))\r
+                    throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));\r
+            }\r
+        }\r
+        catch (exception& ex) {\r
+            m_log.error("error storing assertion along with session: %s", ex.what());\r
+        }\r
+    }\r
+\r
     const char* pid = obj["entity_id"].string();\r
-    m_log.debug("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);\r
+    m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);\r
 \r
     // Transaction Logging\r
-    auto_ptr_char name(nameid.getName());\r
-    TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
+    TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
     Locker locker(xlog);\r
     xlog->log.infoStream() <<\r
         "New session (ID: " <<\r
@@ -359,30 +652,401 @@ string SSCache::insert(
         ") for principal from (IdP: " <<\r
             (pid ? pid : "none") <<\r
         ") at (ClientAddress: " <<\r
-            client_addr <<\r
+            (client_addr ? client_addr : "none") <<\r
         ") with (NameIdentifier: " <<\r
-            name.get() <<\r
+            (name.get() ? name.get() : "none") <<\r
         ")";\r
     \r
+    if (attributes) {\r
+        xlog->log.infoStream() <<\r
+            "Cached the following attributes with session (ID: " <<\r
+                key.get() <<\r
+            ") for (applicationId: " <<\r
+                application.getId() <<\r
+            ") {";\r
+        for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)\r
+            xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";\r
+        xlog->log.info("}");\r
+    }\r
+\r
     return key.get();\r
 }\r
 \r
-Session* SSCache::find(const char* key, const Application& application, const char* client_addr)\r
+Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)\r
 {\r
-    return NULL;\r
+#ifdef _DEBUG\r
+    xmltooling::NDC ndc("find");\r
+#endif\r
+\r
+    m_log.debug("searching for session (%s)", key);\r
+    \r
+    time_t lastAccess;\r
+    string record;\r
+    int ver = m_storage->readText(key, "session", &record, &lastAccess);\r
+    if (!ver)\r
+        return NULL;\r
+    \r
+    m_log.debug("reconstituting session and checking validity");\r
+    \r
+    DDF obj;\r
+    istringstream in(record);\r
+    in >> obj;\r
+    \r
+    if (!XMLString::equals(obj["application_id"].string(), application.getId())) {\r
+        m_log.error("an application (%s) tried to access another application's session", application.getId());\r
+        obj.destroy();\r
+        return NULL;\r
+    }\r
+\r
+    if (client_addr) {\r
+        if (m_log.isDebugEnabled())\r
+            m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());\r
+        if (strcmp(obj["client_addr"].string(),client_addr)) {\r
+            m_log.warn("client address mismatch");\r
+            remove(key, application);\r
+            RetryableProfileException ex(\r
+                "Your IP address ($1) does not match the address recorded at the time the session was established.",\r
+                params(1,client_addr)\r
+                );\r
+            string eid(obj["entity_id"].string());\r
+            obj.destroy();\r
+            if (eid.empty())\r
+                throw ex;\r
+            MetadataProvider* m=application.getMetadataProvider();\r
+            Locker locker(m);\r
+            annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
+        }\r
+    }\r
+\r
+    lastAccess -= m_cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched\r
+    time_t now=time(NULL);\r
+    \r
+    if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {\r
+        m_log.info("session timed out (ID: %s)", key);\r
+        remove(key, application);\r
+        RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
+        string eid(obj["entity_id"].string());\r
+        obj.destroy();\r
+        if (eid.empty())\r
+            throw ex;\r
+        MetadataProvider* m=application.getMetadataProvider();\r
+        Locker locker(m);\r
+        annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
+    }\r
+    \r
+    auto_ptr_XMLCh exp(obj["expires"].string());\r
+    if (exp.get()) {\r
+        DateTime iso(exp.get());\r
+        iso.parseDateTime();\r
+        if (now > iso.getEpoch()) {\r
+            m_log.info("session expired (ID: %s)", key);\r
+            remove(key, application);\r
+            RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
+            string eid(obj["entity_id"].string());\r
+            obj.destroy();\r
+            if (eid.empty())\r
+                throw ex;\r
+            MetadataProvider* m=application.getMetadataProvider();\r
+            Locker locker(m);\r
+            annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
+        }\r
+    }\r
+    \r
+    if (timeout) {\r
+        // Update storage expiration, if possible.\r
+        try {\r
+            m_storage->updateContext(key, now + m_cacheTimeout);\r
+        }\r
+        catch (exception& ex) {\r
+            m_log.error("failed to update session expiration: %s", ex.what());\r
+        }\r
+    }\r
+\r
+    // Finally build the Session object.\r
+    try {\r
+        return new StoredSession(this, obj);\r
+    }\r
+    catch (exception&) {\r
+        obj.destroy();\r
+        throw;\r
+    }\r
 }\r
 \r
-void SSCache::remove(const char* key, const Application& application, const char* client_addr)\r
+void SSCache::remove(const char* key, const Application& application)\r
 {\r
 #ifdef _DEBUG\r
     xmltooling::NDC ndc("remove");\r
 #endif\r
 \r
-    m_log.debug("removing session (%s)", key);\r
+    m_storage->deleteContext(key);\r
+    m_log.info("removed session (%s)", key);\r
 \r
-    m_storage->deleteText(application.getId(), key);\r
-\r
-    TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
+    TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
     Locker locker(xlog);\r
     xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);\r
 }\r
+\r
+void SSCache::remove(\r
+    const saml2md::EntityDescriptor* issuer,\r
+    const saml2::NameID& nameid,\r
+    const char* index,\r
+    const Application& application,\r
+    vector<string>& sessionsKilled\r
+    )\r
+{\r
+#ifdef _DEBUG\r
+    xmltooling::NDC ndc("remove");\r
+#endif\r
+\r
+    auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);\r
+    auto_ptr_char name(nameid.getName());\r
+\r
+    m_log.info(\r
+        "request to logout sessions from (%s) for (%s) for session index (%s)",\r
+        entityID.get() ? entityID.get() : "unknown", name.get(), index ? index : "all"\r
+        );\r
+\r
+    if (strlen(name.get()) > 255)\r
+        const_cast<char*>(name.get())[255] = 0;\r
+\r
+    // Read in potentially matching sessions.\r
+    string record;\r
+    int ver = m_storage->readText("NameID", name.get(), &record);\r
+    if (ver == 0) {\r
+        m_log.debug("no active sessions to remove for supplied issuer and name identifier");\r
+        return;\r
+    }\r
+\r
+    DDF obj;\r
+    DDFJanitor jobj(obj);\r
+    istringstream in(record);\r
+    in >> obj;\r
+\r
+    // The record contains child lists for each known session index.\r
+    DDF key;\r
+    DDF sessions = obj.first();\r
+    while (sessions.islist()) {\r
+        if (!index || !strcmp(sessions.name(), index)) {\r
+            key = sessions.first();\r
+            while (key.isstring()) {\r
+                // Fetch the session for comparison and possible removal.\r
+                Session* session = find(key.string(), application);\r
+                Locker locker(session);\r
+                if (session) {\r
+                    // Same issuer?\r
+                    if (XMLString::equals(session->getEntityID(), entityID.get())) {\r
+                        // Same NameID?\r
+                        if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {\r
+                            sessionsKilled.push_back(key.string());\r
+                            remove(key.string(), application);  // let this throw to detect errors in case the full logout fails?\r
+                            key.destroy();\r
+                        }\r
+                        else {\r
+                            m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());\r
+                        }\r
+                    }\r
+                    else {\r
+                        m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());\r
+                    }\r
+                }\r
+                else {\r
+                    // Session's gone, so...\r
+                    sessionsKilled.push_back(key.string());\r
+                    key.destroy();\r
+                }\r
+                key = sessions.next();\r
+            }\r
+\r
+            // No sessions left for this index?\r
+            if (sessions.first().isnull())\r
+                sessions.destroy();\r
+        }\r
+        sessions = obj.next();\r
+    }\r
+    \r
+    if (obj.first().isnull())\r
+        obj.destroy();\r
+\r
+    // If possible, write back the mapping record (this isn't crucial).\r
+    try {\r
+        if (obj.isnull()) {\r
+            m_storage->deleteText("NameID", name.get());\r
+        }\r
+        else if (!sessionsKilled.empty()) {\r
+            ostringstream out;\r
+            out << obj;\r
+            if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)\r
+                m_log.warn("logout mapping record changed behind us, leaving it alone");\r
+        }\r
+    }\r
+    catch (exception& ex) {\r
+        m_log.error("error updating logout mapping record: %s", ex.what());\r
+    }\r
+}\r
+\r
+bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const\r
+{\r
+    if (!XMLString::equals(n1.getName(), n2.getName()))\r
+        return false;\r
+    \r
+    const XMLCh* s1 = n1.getFormat();\r
+    const XMLCh* s2 = n2.getFormat();\r
+    if (!s1 || !*s1)\r
+        s1 = saml2::NameID::UNSPECIFIED;\r
+    if (!s2 || !*s2)\r
+        s2 = saml2::NameID::UNSPECIFIED;\r
+    if (!XMLString::equals(s1,s2))\r
+        return false;\r
+    \r
+    s1 = n1.getNameQualifier();\r
+    s2 = n2.getNameQualifier();\r
+    if (!s1 || !*s1)\r
+        s1 = idp;\r
+    if (!s2 || !*s2)\r
+        s2 = idp;\r
+    if (!XMLString::equals(s1,s2))\r
+        return false;\r
+\r
+    s1 = n1.getSPNameQualifier();\r
+    s2 = n2.getSPNameQualifier();\r
+    if (!s1 || !*s1)\r
+        s1 = sp;\r
+    if (!s2 || !*s2)\r
+        s2 = sp;\r
+    if (!XMLString::equals(s1,s2))\r
+        return false;\r
+\r
+    return true;\r
+}\r
+\r
+void SSCache::receive(DDF& in, ostream& out)\r
+{\r
+#ifdef _DEBUG\r
+    xmltooling::NDC ndc("receive");\r
+#endif\r
+\r
+    if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
+        const char* key=in["key"].string();\r
+        if (!key)\r
+            throw ListenerException("Required parameters missing for session removal.");\r
+\r
+        const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());\r
+        if (!app)\r
+            throw ListenerException("Application not found, check configuration?");\r
+\r
+        // Do an unversioned read.\r
+        string record;\r
+        time_t lastAccess;\r
+        if (!m_storage->readText(key, "session", &record, &lastAccess)) {\r
+            DDF ret(NULL);\r
+            DDFJanitor jan(ret);\r
+            out << ret;\r
+            return;\r
+        }\r
+\r
+        // Adjust for expiration to recover last access time and check timeout.\r
+        lastAccess -= m_cacheTimeout;\r
+        time_t now=time(NULL);\r
+\r
+        // See if we need to check for a timeout.\r
+        if (in["timeout"].string()) {\r
+            time_t timeout = 0;\r
+            auto_ptr_XMLCh dt(in["timeout"].string());\r
+            DateTime dtobj(dt.get());\r
+            dtobj.parseDateTime();\r
+            timeout = dtobj.getEpoch();\r
+                    \r
+            if (timeout > 0 && now - lastAccess >= timeout) {\r
+                m_log.info("session timed out (ID: %s)", key);\r
+                remove(key,*app);\r
+                throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
+            } \r
+\r
+            // Update storage expiration, if possible.\r
+            try {\r
+                m_storage->updateContext(key, now + m_cacheTimeout);\r
+            }\r
+            catch (exception& ex) {\r
+                m_log.error("failed to update session expiration: %s", ex.what());\r
+            }\r
+        }\r
+            \r
+        // Send the record back.\r
+        out << record;\r
+    }\r
+    else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
+        const char* key=in["key"].string();\r
+        if (!key)\r
+            throw ListenerException("Required parameters missing for session check.");\r
+\r
+        // Do a versioned read.\r
+        string record;\r
+        time_t lastAccess;\r
+        int curver = in["version"].integer();\r
+        int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);\r
+        if (ver == 0) {\r
+            m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);\r
+            throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
+        }\r
+\r
+        // Adjust for expiration to recover last access time and check timeout.\r
+        lastAccess -= m_cacheTimeout;\r
+        time_t now=time(NULL);\r
+\r
+        // See if we need to check for a timeout.\r
+        time_t timeout = 0;\r
+        auto_ptr_XMLCh dt(in["timeout"].string());\r
+        if (dt.get()) {\r
+            DateTime dtobj(dt.get());\r
+            dtobj.parseDateTime();\r
+            timeout = dtobj.getEpoch();\r
+        }\r
+                \r
+        if (timeout > 0 && now - lastAccess >= timeout) {\r
+            m_log.info("session timed out (ID: %s)", key);\r
+            throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
+        } \r
+\r
+        // Update storage expiration, if possible.\r
+        try {\r
+            m_storage->updateContext(key, now + m_cacheTimeout);\r
+        }\r
+        catch (exception& ex) {\r
+            m_log.error("failed to update session expiration: %s", ex.what());\r
+        }\r
+            \r
+        if (ver > curver) {\r
+            // Send the record back.\r
+            out << record;\r
+        }\r
+        else {\r
+            DDF ret(NULL);\r
+            DDFJanitor jan(ret);\r
+            out << ret;\r
+        }\r
+    }\r
+    else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
+        const char* key=in["key"].string();\r
+        if (!key)\r
+            throw ListenerException("Required parameter missing for session removal.");\r
+\r
+        const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());\r
+        if (!app)\r
+            throw ListenerException("Application not found, check configuration?");\r
+\r
+        remove(key,*app);\r
+        DDF ret(NULL);\r
+        DDFJanitor jan(ret);\r
+        out << ret;\r
+    }\r
+    else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
+        const char* key=in["key"].string();\r
+        const char* id=in["id"].string();\r
+        if (!key || !id)\r
+            throw ListenerException("Required parameters missing for assertion retrieval.");\r
+        string token;\r
+        if (!m_storage->readText(key, id, &token, NULL))\r
+            throw FatalProfileException("Assertion not found in cache.");\r
+        out << token;\r
+    }\r
+}\r