2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * StorageServiceSessionCache.cpp
20 * StorageService-based SessionCache implementation.
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
24 * layer their own cache plugin on top of this version either by delegating to it
25 * or using the remoting support. So this version will load sessions directly
26 * from the StorageService, instantiate enough to expose the Session API,
27 * and then delete everything when they're unlocked. All data in memory is always
28 * kept in sync with the StorageService (no lazy updates).
32 #include "Application.h"
33 #include "exceptions.h"
34 #include "ServiceProvider.h"
35 #include "SessionCacheEx.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "remoting/ListenerService.h"
39 #include "util/SPConstants.h"
42 #include <xmltooling/io/HTTPRequest.h>
43 #include <xmltooling/io/HTTPResponse.h>
44 #include <xmltooling/util/DateTime.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/ParserPool.h>
47 #include <xmltooling/util/Threads.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
52 # include <saml/exceptions.h>
53 # include <saml/SAMLConfig.h>
54 # include <saml/saml2/core/Assertions.h>
55 # include <saml/saml2/metadata/Metadata.h>
56 # include <xmltooling/XMLToolingConfig.h>
57 # include <xmltooling/util/StorageService.h>
58 using namespace opensaml::saml2md;
61 # include <xmltooling/util/DateTime.h>
64 using namespace shibsp;
65 using namespace opensaml;
66 using namespace xmltooling;
72 class SSCache : public SessionCacheEx
74 ,public virtual Remoted
78 SSCache(const DOMElement* e);
82 void receive(DDF& in, ostream& out);
85 const Application& app,
86 const HTTPRequest& httpRequest,
87 HTTPResponse& httpResponse,
89 const saml2md::EntityDescriptor* issuer=nullptr,
90 const XMLCh* protocol=nullptr,
91 const saml2::NameID* nameid=nullptr,
92 const XMLCh* authn_instant=nullptr,
93 const XMLCh* session_index=nullptr,
94 const XMLCh* authncontext_class=nullptr,
95 const XMLCh* authncontext_decl=nullptr,
96 const vector<const Assertion*>* tokens=nullptr,
97 const vector<Attribute*>* attributes=nullptr
99 vector<string>::size_type logout(
100 const Application& app,
101 const saml2md::EntityDescriptor* issuer,
102 const saml2::NameID& nameid,
103 const set<string>* indexes,
105 vector<string>& sessions
108 const Application& app,
109 const xmltooling::HTTPRequest& request,
110 const saml2md::EntityDescriptor* issuer,
111 const saml2::NameID& nameid,
112 const set<string>* indexes
115 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
116 void remove(const Application& app, const char* key);
119 string active(const Application& app, const xmltooling::HTTPRequest& request) {
120 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
121 const char* session_id = request.getCookie(shib_cookie.first.c_str());
122 return (session_id ? session_id : "");
125 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
126 string id = active(app, request);
128 return find(app, id.c_str(), client_addr, timeout);
132 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
133 string id = active(app, request);
137 Session* session = find(app, id.c_str(), client_addr, timeout);
140 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
142 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
143 string exp(shib_cookie.second);
144 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
145 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
149 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
151 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
152 string exp(shib_cookie.second);
153 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
154 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
161 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr) {
162 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
163 const char* session_id = request.getCookie(shib_cookie.first.c_str());
164 if (session_id && *session_id) {
166 string exp(shib_cookie.second);
167 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
168 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
170 remove(app, session_id);
174 unsigned long getCacheTimeout(const Application& app) {
175 // Computes offset for adjusting expiration of sessions.
176 // This can either be static, or dynamic based on the per-app session timeout.
178 return m_cacheTimeout;
179 pair<bool,unsigned int> timeout;
180 const PropertySet* props = app.getPropertySet("Sessions");
182 timeout = props->getUnsignedInt("timeout");
184 timeout.second = 3600;
186 return timeout.second + m_cacheAllowance;
192 StorageService* m_storage;
193 StorageService* m_storage_lite;
198 // maintain back-mappings of NameID/SessionIndex -> session key
199 void insert(const char* key, time_t expires, const char* name, const char* index);
200 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
202 bool m_cacheAssertions;
204 const DOMElement* m_root; // Only valid during initialization
205 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
207 // inproc means we buffer sessions in memory
209 map<string,StoredSession*> m_hashtable;
211 // management of buffered sessions
212 void dormant(const char* key);
213 static void* cleanup_fn(void*);
216 CondWait* shutdown_wait;
217 Thread* cleanup_thread;
220 class StoredSession : public virtual Session
223 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
227 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
228 auto_ptr_XMLCh exp(m_obj["expires"].string());
230 DateTime iso(exp.get());
232 m_expires = iso.getEpoch();
236 const char* nameid = obj["nameid"].string();
238 // Parse and bind the document into an XMLObject.
239 istringstream instr(nameid);
240 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
241 XercesJanitor<DOMDocument> janitor(doc);
242 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
243 n->unmarshall(doc->getDocumentElement(), true);
245 m_nameid = n.release();
249 m_lock = Mutex::create();
255 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
258 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
274 const char* getID() const {
277 const char* getApplicationID() const {
278 return m_obj["application_id"].string();
280 const char* getClientAddress() const {
281 return m_obj["client_addr"].string();
283 const char* getEntityID() const {
284 return m_obj["entity_id"].string();
286 const char* getProtocol() const {
287 return m_obj["protocol"].string();
289 const char* getAuthnInstant() const {
290 return m_obj["authn_instant"].string();
293 const saml2::NameID* getNameID() const {
297 const char* getSessionIndex() const {
298 return m_obj["session_index"].string();
300 const char* getAuthnContextClassRef() const {
301 return m_obj["authncontext_class"].string();
303 const char* getAuthnContextDeclRef() const {
304 return m_obj["authncontext_decl"].string();
306 const vector<Attribute*>& getAttributes() const {
307 if (m_attributes.empty())
308 unmarshallAttributes();
311 const multimap<string,const Attribute*>& getIndexedAttributes() const {
312 if (m_attributeIndex.empty()) {
313 if (m_attributes.empty())
314 unmarshallAttributes();
315 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
316 const vector<string>& aliases = (*a)->getAliases();
317 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
318 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
321 return m_attributeIndex;
323 const vector<const char*>& getAssertionIDs() const {
325 DDF ids = m_obj["assertions"];
326 DDF id = ids.first();
327 while (id.isstring()) {
328 m_ids.push_back(id.string());
335 void validate(const Application& application, const char* client_addr, time_t* timeout);
338 void addAttributes(const vector<Attribute*>& attributes);
339 const Assertion* getAssertion(const char* id) const;
340 void addAssertion(Assertion* assertion);
343 time_t getExpiration() const { return m_expires; }
344 time_t getLastAccess() const { return m_lastAccess; }
347 void unmarshallAttributes() const;
351 saml2::NameID* m_nameid;
352 mutable map<string,Assertion*> m_tokens;
354 mutable vector<Attribute*> m_attributes;
355 mutable multimap<string,const Attribute*> m_attributeIndex;
356 mutable vector<const char*> m_ids;
359 time_t m_expires,m_lastAccess;
363 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
365 return new SSCache(e);
369 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
371 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
374 void SHIBSP_API shibsp::registerSessionCaches()
376 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
387 void StoredSession::unmarshallAttributes() const
389 Attribute* attribute;
390 DDF attrs = m_obj["attributes"];
391 DDF attr = attrs.first();
392 while (!attr.isnull()) {
394 attribute = Attribute::unmarshall(attr);
395 m_attributes.push_back(attribute);
396 if (m_cache->m_log.isDebugEnabled())
397 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
398 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
400 catch (AttributeException& ex) {
401 const char* id = attr.first().name();
402 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
408 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
410 time_t now = time(nullptr);
414 if (now > m_expires) {
415 m_cache->m_log.info("session expired (ID: %s)", getID());
416 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
422 if (m_cache->m_log.isDebugEnabled())
423 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
424 if (!XMLString::equals(getClientAddress(),client_addr)) {
425 m_cache->m_log.warn("client address mismatch");
426 throw RetryableProfileException(
427 "Your IP address ($1) does not match the address recorded at the time the session was established.",
428 params(1,client_addr)
436 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
437 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
440 in.addmember("key").string(getID());
441 in.addmember("version").integer(m_obj["version"].integer());
443 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
444 #ifndef HAVE_GMTIME_R
445 struct tm* ptime=gmtime(timeout);
448 struct tm* ptime=gmtime_r(timeout,&res);
451 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
452 in.addmember("timeout").string(timebuf);
456 out=app.getServiceProvider().getListenerService()->send(in);
463 if (out.isstruct()) {
464 // We got an updated record back.
466 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
467 m_attributes.clear();
468 m_attributeIndex.clear();
475 if (!m_cache->m_storage)
476 throw ConfigurationException("Session touch requires a StorageService.");
478 // Do a versioned read.
481 int curver = m_obj["version"].integer();
482 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
484 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
485 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
488 // Adjust for expiration to recover last access time and check timeout.
489 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
490 lastAccess -= cacheTimeout;
491 if (*timeout > 0 && now - lastAccess >= *timeout) {
492 m_cache->m_log.info("session timed out (ID: %s)", getID());
493 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
496 // Update storage expiration, if possible.
498 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
500 catch (exception& ex) {
501 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
505 // We got an updated record back.
507 istringstream in(record);
510 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
511 m_attributes.clear();
512 m_attributeIndex.clear();
517 throw ConfigurationException("Session touch requires a StorageService.");
526 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
529 xmltooling::NDC ndc("addAttributes");
532 if (!m_cache->m_storage)
533 throw ConfigurationException("Session modification requires a StorageService.");
535 m_cache->m_log.debug("adding attributes to session (%s)", getID());
540 DDF attrs = m_obj["attributes"];
542 attrs = m_obj.addmember("attributes").list();
543 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
544 attr = (*a)->marshall();
548 // Tentatively increment the version.
549 m_obj["version"].integer(m_obj["version"].integer()+1);
553 string record(str.str());
556 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
559 // Roll back modification to record.
560 m_obj["version"].integer(m_obj["version"].integer()-1);
561 vector<Attribute*>::size_type count = attributes.size();
563 attrs.last().destroy();
568 // Roll back modification to record.
569 m_obj["version"].integer(m_obj["version"].integer()-1);
570 vector<Attribute*>::size_type count = attributes.size();
572 attrs.last().destroy();
575 // Fatal problem with update.
576 throw IOException("Unable to update stored session.");
580 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
581 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
583 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
584 throw IOException("Unable to read back stored session.");
589 istringstream in(record);
593 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
594 m_attributes.clear();
595 m_attributeIndex.clear();
596 newobj["version"].integer(ver);
602 } while (ver < 0); // negative indicates a sync issue so we retry
604 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
606 xlog->log.infoStream() <<
607 "Added the following attributes to session (ID: " <<
609 ") for (applicationId: " <<
610 m_obj["application_id"].string() <<
612 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
613 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
616 // We own them now, so clean them up.
617 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
620 const Assertion* StoredSession::getAssertion(const char* id) const
622 if (!m_cache->m_storage)
623 throw ConfigurationException("Assertion retrieval requires a StorageService.");
625 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
626 if (i!=m_tokens.end())
630 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
631 throw FatalProfileException("Assertion not found in cache.");
633 // Parse and bind the document into an XMLObject.
634 istringstream instr(tokenstr);
635 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
636 XercesJanitor<DOMDocument> janitor(doc);
637 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
640 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
642 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
644 // Transfer ownership to us.
650 void StoredSession::addAssertion(Assertion* assertion)
653 xmltooling::NDC ndc("addAssertion");
656 if (!m_cache->m_storage)
657 throw ConfigurationException("Session modification requires a StorageService.");
660 throw FatalProfileException("Unknown object type passed to session for storage.");
662 auto_ptr_char id(assertion->getID());
664 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
667 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
668 throw IOException("Unable to load expiration time for stored session.");
670 ostringstream tokenstr;
671 tokenstr << *assertion;
672 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
673 throw IOException("Attempted to insert duplicate assertion ID into session.");
677 DDF token = DDF(nullptr).string(id.get());
678 m_obj["assertions"].add(token);
680 // Tentatively increment the version.
681 m_obj["version"].integer(m_obj["version"].integer()+1);
685 string record(str.str());
688 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
692 m_obj["version"].integer(m_obj["version"].integer()-1);
693 m_cache->m_storage->deleteText(getID(), id.get());
699 m_obj["version"].integer(m_obj["version"].integer()-1);
702 // Fatal problem with update.
703 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
704 m_cache->m_storage->deleteText(getID(), id.get());
705 throw IOException("Unable to update stored session.");
709 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
710 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
712 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
713 m_cache->m_storage->deleteText(getID(), id.get());
714 throw IOException("Unable to read back stored session.");
719 istringstream in(record);
723 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
724 m_attributes.clear();
725 m_attributeIndex.clear();
726 newobj["version"].integer(ver);
732 } while (ver < 0); // negative indicates a sync issue so we retry
737 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
740 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
741 id.get(), m_obj["application_id"].string(), getID()
747 SessionCache::SessionCache()
751 SessionCache::~SessionCache()
755 SessionCacheEx::SessionCacheEx()
759 SessionCacheEx::~SessionCacheEx()
763 SSCache::SSCache(const DOMElement* e)
764 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
766 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
768 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
769 m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
771 SPConfig& conf = SPConfig::getConfig();
772 inproc = conf.isEnabled(SPConfig::InProcess);
774 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
775 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
776 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
777 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
778 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
779 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);
781 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
782 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
784 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
787 if (conf.isEnabled(SPConfig::OutOfProcess)) {
788 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
790 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
792 m_log.info("bound to StorageService (%s)", ssid.c_str());
794 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
797 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
799 m_log.info("bound to arbitrary StorageService");
801 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
804 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
806 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
808 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
810 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
812 if (!m_storage_lite) {
813 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
814 m_storage_lite = m_storage;
817 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
821 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
823 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
824 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
825 m_lock = RWLock::create();
826 shutdown_wait = CondWait::create();
827 cleanup_thread = Thread::create(&cleanup_fn, this);
831 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
832 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
833 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
834 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
837 m_log.info("no ListenerService available, cache remoting disabled");
846 // Shut down the cleanup thread and let it know...
848 shutdown_wait->signal();
849 cleanup_thread->join(nullptr);
851 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
854 delete cleanup_thread;
855 delete shutdown_wait;
859 SPConfig& conf = SPConfig::getConfig();
860 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
861 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
862 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
863 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
864 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
874 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
875 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
876 m_storage->deleteString("SessionCacheTest", temp.get());
879 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
882 if (strlen(name) > 255) {
883 dup = string(name).substr(0,255);
888 DDFJanitor jobj(obj);
890 // Since we can't guarantee uniqueness, check for an existing record.
893 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
895 // Existing record, so we need to unmarshall it.
896 istringstream in(record);
901 obj = DDF(nullptr).structure();
904 if (!index || !*index)
906 DDF sessions = obj.addmember(index);
907 if (!sessions.islist())
909 DDF session = DDF(nullptr).string(key);
910 sessions.add(session);
912 // Remarshall the record.
916 // Try and store it back...
918 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
920 // Out of sync, or went missing, so retry.
921 return insert(key, expires, name, index);
924 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
925 // Hit a dup, so just retry, hopefully hitting the other branch.
926 return insert(key, expires, name, index);
930 void SSCache::insert(
931 const Application& app,
932 const HTTPRequest& httpRequest,
933 HTTPResponse& httpResponse,
935 const saml2md::EntityDescriptor* issuer,
936 const XMLCh* protocol,
937 const saml2::NameID* nameid,
938 const XMLCh* authn_instant,
939 const XMLCh* session_index,
940 const XMLCh* authncontext_class,
941 const XMLCh* authncontext_decl,
942 const vector<const Assertion*>* tokens,
943 const vector<Attribute*>* attributes
947 xmltooling::NDC ndc("insert");
950 throw ConfigurationException("SessionCache insertion requires a StorageService.");
952 m_log.debug("creating new session");
954 time_t now = time(nullptr);
955 auto_ptr_char index(session_index);
956 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
957 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
960 // Check for a pending logout.
962 strncpy(namebuf, name.get(), 255);
965 int ver = m_storage_lite->readText("Logout", namebuf, &pending);
968 DDFJanitor jpend(pendobj);
969 istringstream pstr(pending);
971 // IdP.SP.index contains logout expiration, if any.
972 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
973 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
974 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
975 logexpstr = deadmenwalking["_shibnull"].string();
977 auto_ptr_XMLCh dt(logexpstr);
978 DateTime dtobj(dt.get());
979 dtobj.parseDateTime();
980 time_t logexp = dtobj.getEpoch();
981 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
982 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
987 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
989 // Store session properties in DDF.
990 DDF obj = DDF(key.get()).structure();
991 DDFJanitor entryobj(obj);
992 obj.addmember("version").integer(1);
993 obj.addmember("application_id").string(app.getId());
995 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
996 #ifndef HAVE_GMTIME_R
997 struct tm* ptime=gmtime(&expires);
1000 struct tm* ptime=gmtime_r(&expires,&res);
1003 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1004 obj.addmember("expires").string(timebuf);
1006 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
1008 obj.addmember("entity_id").string(entity_id.get());
1010 auto_ptr_char prot(protocol);
1011 obj.addmember("protocol").string(prot.get());
1013 if (authn_instant) {
1014 auto_ptr_char instant(authn_instant);
1015 obj.addmember("authn_instant").string(instant.get());
1018 obj.addmember("session_index").string(index.get());
1019 if (authncontext_class) {
1020 auto_ptr_char ac(authncontext_class);
1021 obj.addmember("authncontext_class").string(ac.get());
1023 if (authncontext_decl) {
1024 auto_ptr_char ad(authncontext_decl);
1025 obj.addmember("authncontext_decl").string(ad.get());
1029 ostringstream namestr;
1031 obj.addmember("nameid").string(namestr.str().c_str());
1034 if (tokens && m_cacheAssertions) {
1035 obj.addmember("assertions").list();
1036 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1037 auto_ptr_char tokenid((*t)->getID());
1038 DDF tokid = DDF(nullptr).string(tokenid.get());
1039 obj["assertions"].add(tokid);
1045 DDF attrlist = obj.addmember("attributes").list();
1046 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1047 attr = (*a)->marshall();
1052 ostringstream record;
1055 m_log.debug("storing new session...");
1056 unsigned long cacheTimeout = getCacheTimeout(app);
1057 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1058 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1060 // Store the reverse mapping for logout.
1063 insert(key.get(), expires, name.get(), index.get());
1065 catch (exception& ex) {
1066 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1069 if (tokens && m_cacheAssertions) {
1071 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1072 ostringstream tokenstr;
1074 auto_ptr_char tokenid((*t)->getID());
1075 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1076 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1079 catch (exception& ex) {
1080 m_log.error("error storing assertion along with session: %s", ex.what());
1084 const char* pid = obj["entity_id"].string();
1085 const char* prot = obj["protocol"].string();
1086 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1087 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1089 // Transaction Logging
1090 string primaryAssertionID("none");
1091 if (m_cacheAssertions) {
1093 primaryAssertionID = obj["assertions"].first().string();
1096 auto_ptr_char tokenid(tokens->front()->getID());
1097 primaryAssertionID = tokenid.get();
1099 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1100 Locker locker(xlog);
1101 xlog->log.infoStream() <<
1102 "New session (ID: " <<
1104 ") with (applicationId: " <<
1106 ") for principal from (IdP: " <<
1107 (pid ? pid : "none") <<
1108 ") at (ClientAddress: " <<
1109 httpRequest.getRemoteAddr() <<
1110 ") with (NameIdentifier: " <<
1111 (nameid ? name.get() : "none") <<
1112 ") using (Protocol: " <<
1113 (prot ? prot : "none") <<
1114 ") from (AssertionID: " <<
1115 primaryAssertionID <<
1119 xlog->log.infoStream() <<
1120 "Cached the following attributes with session (ID: " <<
1122 ") for (applicationId: " <<
1125 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1126 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1127 xlog->log.info("}");
1130 time_t cookieLifetime = 0;
1131 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1132 string k(key.get());
1133 k += shib_cookie.second;
1135 if (cookieLifetime > 0) {
1136 cookieLifetime += now;
1137 #ifndef HAVE_GMTIME_R
1138 ptime=gmtime(&cookieLifetime);
1140 ptime=gmtime_r(&cookieLifetime,&res);
1142 char cookietimebuf[64];
1143 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1147 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1150 bool SSCache::matches(
1151 const Application& app,
1152 const xmltooling::HTTPRequest& request,
1153 const saml2md::EntityDescriptor* issuer,
1154 const saml2::NameID& nameid,
1155 const set<string>* indexes
1158 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1160 Session* session = find(app, request);
1162 Locker locker(session, false);
1163 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1164 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1165 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1169 catch (exception& ex) {
1170 m_log.error("error while matching session: %s", ex.what());
1175 vector<string>::size_type SSCache::logout(
1176 const Application& app,
1177 const saml2md::EntityDescriptor* issuer,
1178 const saml2::NameID& nameid,
1179 const set<string>* indexes,
1181 vector<string>& sessionsKilled
1185 xmltooling::NDC ndc("logout");
1189 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1191 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1192 auto_ptr_char name(nameid.getName());
1194 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1196 if (strlen(name.get()) > 255)
1197 const_cast<char*>(name.get())[255] = 0;
1200 DDFJanitor jobj(obj);
1205 // Record the logout to prevent post-delivered assertions.
1206 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1207 #ifndef HAVE_GMTIME_R
1208 struct tm* ptime=gmtime(&expires);
1211 struct tm* ptime=gmtime_r(&expires,&res);
1214 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1217 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1219 istringstream lin(record);
1223 obj = DDF(nullptr).structure();
1226 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1227 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1229 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1230 root.addmember(x->c_str()).string(timebuf);
1233 root.addmember("_shibnull").string(timebuf);
1241 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1243 // Out of sync, or went missing, so retry.
1244 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1247 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1248 // Hit a dup, so just retry, hopefully hitting the other branch.
1249 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1256 // Read in potentially matching sessions.
1257 ver = m_storage_lite->readText("NameID", name.get(), &record);
1259 m_log.debug("no active sessions to logout for supplied issuer and subject");
1263 istringstream in(record);
1266 // The record contains child lists for each known session index.
1268 DDF sessions = obj.first();
1269 while (sessions.islist()) {
1270 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1271 key = sessions.first();
1272 while (key.isstring()) {
1273 // Fetch the session for comparison.
1274 Session* session = nullptr;
1276 session = find(app, key.string());
1278 catch (exception& ex) {
1279 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1283 Locker locker(session, false);
1285 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1287 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1288 sessionsKilled.push_back(key.string());
1292 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1296 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1300 // Session's gone, so...
1301 sessionsKilled.push_back(key.string());
1304 key = sessions.next();
1307 // No sessions left for this index?
1308 if (sessions.first().isnull())
1311 sessions = obj.next();
1314 if (obj.first().isnull())
1317 // If possible, write back the mapping record (this isn't crucial).
1320 m_storage_lite->deleteText("NameID", name.get());
1322 else if (!sessionsKilled.empty()) {
1325 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1326 m_log.warn("logout mapping record changed behind us, leaving it alone");
1329 catch (exception& ex) {
1330 m_log.error("error updating logout mapping record: %s", ex.what());
1333 return sessionsKilled.size();
1336 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1338 if (!XMLString::equals(n1.getName(), n2.getName()))
1341 const XMLCh* s1 = n1.getFormat();
1342 const XMLCh* s2 = n2.getFormat();
1344 s1 = saml2::NameID::UNSPECIFIED;
1346 s2 = saml2::NameID::UNSPECIFIED;
1347 if (!XMLString::equals(s1,s2))
1350 s1 = n1.getNameQualifier();
1351 s2 = n2.getNameQualifier();
1356 if (!XMLString::equals(s1,s2))
1359 s1 = n1.getSPNameQualifier();
1360 s2 = n2.getSPNameQualifier();
1365 if (!XMLString::equals(s1,s2))
1373 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1376 xmltooling::NDC ndc("find");
1378 StoredSession* session=nullptr;
1381 m_log.debug("searching local cache for session (%s)", key);
1383 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1384 if (i!=m_hashtable.end()) {
1385 // Save off and lock the session.
1386 session = i->second;
1389 m_log.debug("session found locally, validating it for use");
1397 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1398 m_log.debug("session not found locally, remoting the search");
1399 // Remote the request.
1400 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1403 in.addmember("key").string(key);
1404 in.addmember("application_id").string(app.getId());
1405 if (timeout && *timeout) {
1406 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1407 #ifndef HAVE_GMTIME_R
1408 struct tm* ptime=gmtime(timeout);
1411 struct tm* ptime=gmtime_r(timeout,&res);
1414 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1415 in.addmember("timeout").string(timebuf);
1419 out=app.getServiceProvider().getListenerService()->send(in);
1420 if (!out.isstruct()) {
1422 m_log.debug("session not found in remote cache");
1426 // Wrap the results in a local entry and save it.
1427 session = new StoredSession(this, out);
1428 // The remote end has handled timeout issues, we handle address and expiration checks.
1437 // We're out of process, so we can search the storage service directly.
1440 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1442 m_log.debug("searching for session (%s)", key);
1447 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1451 m_log.debug("reconstituting session and checking validity");
1453 istringstream in(record);
1456 unsigned long cacheTimeout = getCacheTimeout(app);
1457 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1458 time_t now=time(nullptr);
1460 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1461 m_log.info("session timed out (ID: %s)", key);
1463 const char* eid = obj["entity_id"].string();
1466 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1470 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1474 // Update storage expiration, if possible.
1476 m_storage->updateContext(key, now + cacheTimeout);
1478 catch (exception& ex) {
1479 m_log.error("failed to update session expiration: %s", ex.what());
1483 // Wrap the results in a local entry and save it.
1484 session = new StoredSession(this, obj);
1485 // We handled timeout issues, still need to handle address and expiration checks.
1488 throw ConfigurationException("SessionCache search requires a StorageService.");
1493 // Lock for writing and repeat the search to avoid duplication.
1495 SharedLock shared(m_lock, false);
1496 if (m_hashtable.count(key)) {
1497 // We're using an existing session entry.
1499 session = m_hashtable[key];
1503 m_hashtable[key]=session;
1509 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1510 m_log.error("an application (%s) tried to access another application's session", app.getId());
1515 // Verify currency and update the timestamp if indicated by caller.
1517 session->validate(app, client_addr, timeout);
1528 void SSCache::remove(const Application& app, const char* key)
1531 xmltooling::NDC ndc("remove");
1533 // Take care of local copy.
1537 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1538 // Remove the session from storage directly.
1540 m_storage->deleteContext(key);
1541 m_log.info("removed session (%s)", key);
1543 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1544 Locker locker(xlog);
1545 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1547 throw ConfigurationException("SessionCache removal requires a StorageService.");
1551 // Remote the request.
1552 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1555 in.addmember("key").string(key);
1556 in.addmember("application_id").string(app.getId());
1558 DDF out = app.getServiceProvider().getListenerService()->send(in);
1563 void SSCache::dormant(const char* key)
1566 xmltooling::NDC ndc("dormant");
1569 m_log.debug("deleting local copy of session (%s)", key);
1571 // lock the cache for writing, which means we know nobody is sitting in find()
1574 // grab the entry from the table
1575 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1576 if (i==m_hashtable.end()) {
1581 // ok, remove the entry and lock it
1582 StoredSession* entry=i->second;
1583 m_hashtable.erase(key);
1589 // we can release the cache entry lock because we know we're not in the cache anymore
1595 void* SSCache::cleanup_fn(void* p)
1598 xmltooling::NDC ndc("cleanup");
1601 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1604 // First, let's block all signals
1605 Thread::mask_all_signals();
1608 auto_ptr<Mutex> mutex(Mutex::create());
1610 // Load our configuration details...
1611 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1612 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1613 int rerun_timer = 900;
1615 rerun_timer = XMLString::parseInt(tag);
1616 if (rerun_timer <= 0)
1622 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1624 while (!pcache->shutdown) {
1625 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1626 if (pcache->shutdown)
1629 // Ok, let's run through the cleanup process and clean out
1630 // really old sessions. This is a two-pass process. The
1631 // first pass is done holding a read-lock while we iterate over
1632 // the cache. The second pass doesn't need a lock because
1633 // the 'deletes' will lock the cache.
1635 // Pass 1: iterate over the map and find all entries that have not been
1636 // used in the allotted timeout.
1637 vector<string> stale_keys;
1638 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1640 pcache->m_log.debug("cleanup thread running");
1642 pcache->m_lock->rdlock();
1643 for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1644 // If the last access was BEFORE the stale timeout...
1646 time_t last=i->second->getLastAccess();
1647 i->second->unlock();
1649 stale_keys.push_back(i->first);
1651 pcache->m_lock->unlock();
1653 if (!stale_keys.empty()) {
1654 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1656 // Pass 2: walk through the list of stale entries and remove them from the cache
1657 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1658 pcache->dormant(j->c_str());
1661 pcache->m_log.debug("cleanup thread completed");
1664 pcache->m_log.info("cleanup thread exiting");
1672 void SSCache::receive(DDF& in, ostream& out)
1675 xmltooling::NDC ndc("receive");
1677 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1679 throw ListenerException("Application not found, check configuration?");
1681 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1682 const char* key=in["key"].string();
1684 throw ListenerException("Required parameters missing for session lookup.");
1686 // Do an unversioned read.
1689 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1691 DDFJanitor jan(ret);
1696 // Adjust for expiration to recover last access time and check timeout.
1697 unsigned long cacheTimeout = getCacheTimeout(*app);
1698 lastAccess -= cacheTimeout;
1699 time_t now=time(nullptr);
1701 // See if we need to check for a timeout.
1702 if (in["timeout"].string()) {
1704 auto_ptr_XMLCh dt(in["timeout"].string());
1705 DateTime dtobj(dt.get());
1706 dtobj.parseDateTime();
1707 timeout = dtobj.getEpoch();
1709 if (timeout > 0 && now - lastAccess >= timeout) {
1710 m_log.info("session timed out (ID: %s)", key);
1712 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1715 // Update storage expiration, if possible.
1717 m_storage->updateContext(key, now + cacheTimeout);
1719 catch (exception& ex) {
1720 m_log.error("failed to update session expiration: %s", ex.what());
1724 // Send the record back.
1727 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1728 const char* key=in["key"].string();
1730 throw ListenerException("Required parameters missing for session check.");
1732 // Do a versioned read.
1735 int curver = in["version"].integer();
1736 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1738 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1739 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1742 // Adjust for expiration to recover last access time and check timeout.
1743 unsigned long cacheTimeout = getCacheTimeout(*app);
1744 lastAccess -= cacheTimeout;
1745 time_t now=time(nullptr);
1747 // See if we need to check for a timeout.
1749 auto_ptr_XMLCh dt(in["timeout"].string());
1751 DateTime dtobj(dt.get());
1752 dtobj.parseDateTime();
1753 timeout = dtobj.getEpoch();
1756 if (timeout > 0 && now - lastAccess >= timeout) {
1757 m_log.info("session timed out (ID: %s)", key);
1758 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1761 // Update storage expiration, if possible.
1763 m_storage->updateContext(key, now + cacheTimeout);
1765 catch (exception& ex) {
1766 m_log.error("failed to update session expiration: %s", ex.what());
1770 // Send the record back.
1775 DDFJanitor jan(ret);
1779 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1780 const char* key=in["key"].string();
1782 throw ListenerException("Required parameter missing for session removal.");
1786 DDFJanitor jan(ret);