2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * StorageServiceSessionCache.cpp
24 * StorageService-based SessionCache implementation.
26 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
27 * and avoids extra parsing steps, I'm assuming that systems that require such can
28 * layer their own cache plugin on top of this version either by delegating to it
29 * or using the remoting support. So this version will load sessions directly
30 * from the StorageService, instantiate enough to expose the Session API,
31 * and then delete everything when they're unlocked. All data in memory is always
32 * kept in sync with the StorageService (no lazy updates).
36 #include "Application.h"
37 #include "exceptions.h"
38 #include "ServiceProvider.h"
39 #include "SessionCacheEx.h"
40 #include "TransactionLog.h"
41 #include "attribute/Attribute.h"
42 #include "handler/RemotedHandler.h"
43 #include "remoting/ListenerService.h"
44 #include "util/SPConstants.h"
47 #include <xmltooling/io/HTTPRequest.h>
48 #include <xmltooling/io/HTTPResponse.h>
49 #include <xmltooling/util/DateTime.h>
50 #include <xmltooling/util/NDC.h>
51 #include <xmltooling/util/ParserPool.h>
52 #include <xmltooling/util/Threads.h>
53 #include <xmltooling/util/XMLHelper.h>
54 #include <xercesc/util/XMLUniDefs.hpp>
57 # include <saml/exceptions.h>
58 # include <saml/SAMLConfig.h>
59 # include <saml/saml2/core/Assertions.h>
60 # include <saml/saml2/metadata/Metadata.h>
61 # include <xmltooling/XMLToolingConfig.h>
62 # include <xmltooling/util/StorageService.h>
63 using namespace opensaml::saml2md;
66 # include <xmltooling/util/DateTime.h>
69 using namespace shibsp;
70 using namespace opensaml;
71 using namespace xmltooling;
77 class SSCache : public SessionCacheEx
79 ,public virtual Remoted
83 SSCache(const DOMElement* e);
87 void receive(DDF& in, ostream& out);
90 const Application& app,
91 const HTTPRequest& httpRequest,
92 HTTPResponse& httpResponse,
94 const saml2md::EntityDescriptor* issuer=nullptr,
95 const XMLCh* protocol=nullptr,
96 const saml2::NameID* nameid=nullptr,
97 const XMLCh* authn_instant=nullptr,
98 const XMLCh* session_index=nullptr,
99 const XMLCh* authncontext_class=nullptr,
100 const XMLCh* authncontext_decl=nullptr,
101 const vector<const Assertion*>* tokens=nullptr,
102 const vector<Attribute*>* attributes=nullptr
104 vector<string>::size_type logout(
105 const Application& app,
106 const saml2md::EntityDescriptor* issuer,
107 const saml2::NameID& nameid,
108 const set<string>* indexes,
110 vector<string>& sessions
113 const Application& app,
114 const HTTPRequest& request,
115 const saml2md::EntityDescriptor* issuer,
116 const saml2::NameID& nameid,
117 const set<string>* indexes
120 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
121 void remove(const Application& app, const char* key);
124 string active(const Application& app, const HTTPRequest& request) {
125 if (!m_inboundHeader.empty()) {
126 string session_id = request.getHeader(m_inboundHeader.c_str());
127 if (!session_id.empty())
130 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
131 const char* session_id = request.getCookie(shib_cookie.first.c_str());
132 return (session_id ? session_id : "");
135 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
136 string id = active(app, request);
138 return find(app, id.c_str(), client_addr, timeout);
142 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
143 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
145 unsigned long getCacheTimeout(const Application& app) {
146 // Computes offset for adjusting expiration of sessions.
147 // This can either be static, or dynamic based on the per-app session timeout.
149 return m_cacheTimeout;
150 pair<bool,unsigned int> timeout = pair<bool,unsigned int>(false, 3600);
151 const PropertySet* props = app.getPropertySet("Sessions");
153 timeout = props->getUnsignedInt("timeout");
155 timeout.second = 3600;
157 return timeout.second + m_cacheAllowance;
163 StorageService* m_storage;
164 StorageService* m_storage_lite;
169 // maintain back-mappings of NameID/SessionIndex -> session key
170 void insert(const char* key, time_t expires, const char* name, const char* index);
171 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
173 bool m_cacheAssertions;
175 const DOMElement* m_root; // Only valid during initialization
176 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
177 string m_inboundHeader,m_outboundHeader;
179 // inproc means we buffer sessions in memory
181 map<string,StoredSession*> m_hashtable;
183 // management of buffered sessions
184 void dormant(const char* key);
185 static void* cleanup_fn(void*);
188 CondWait* shutdown_wait;
189 Thread* cleanup_thread;
192 class StoredSession : public virtual Session
195 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
199 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
200 auto_ptr_XMLCh exp(m_obj["expires"].string());
202 DateTime iso(exp.get());
204 m_expires = iso.getEpoch();
208 const char* nameid = obj["nameid"].string();
210 // Parse and bind the document into an XMLObject.
211 istringstream instr(nameid);
212 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
213 XercesJanitor<DOMDocument> janitor(doc);
214 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
215 n->unmarshall(doc->getDocumentElement(), true);
217 m_nameid = n.release();
221 m_lock = Mutex::create();
227 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
230 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
246 const char* getID() const {
249 const char* getApplicationID() const {
250 return m_obj["application_id"].string();
252 const char* getClientAddress() const {
253 return m_obj["client_addr"].string();
255 const char* getEntityID() const {
256 return m_obj["entity_id"].string();
258 const char* getProtocol() const {
259 return m_obj["protocol"].string();
261 const char* getAuthnInstant() const {
262 return m_obj["authn_instant"].string();
265 const saml2::NameID* getNameID() const {
269 const char* getSessionIndex() const {
270 return m_obj["session_index"].string();
272 const char* getAuthnContextClassRef() const {
273 return m_obj["authncontext_class"].string();
275 const char* getAuthnContextDeclRef() const {
276 return m_obj["authncontext_decl"].string();
278 const vector<Attribute*>& getAttributes() const {
279 if (m_attributes.empty())
280 unmarshallAttributes();
283 const multimap<string,const Attribute*>& getIndexedAttributes() const {
284 if (m_attributeIndex.empty()) {
285 if (m_attributes.empty())
286 unmarshallAttributes();
287 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
288 const vector<string>& aliases = (*a)->getAliases();
289 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
290 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
293 return m_attributeIndex;
295 const vector<const char*>& getAssertionIDs() const {
297 DDF ids = m_obj["assertions"];
298 DDF id = ids.first();
299 while (id.isstring()) {
300 m_ids.push_back(id.string());
307 void validate(const Application& application, const char* client_addr, time_t* timeout);
310 void addAttributes(const vector<Attribute*>& attributes);
311 const Assertion* getAssertion(const char* id) const;
312 void addAssertion(Assertion* assertion);
315 time_t getExpiration() const { return m_expires; }
316 time_t getLastAccess() const { return m_lastAccess; }
319 void unmarshallAttributes() const;
323 saml2::NameID* m_nameid;
324 mutable map<string,Assertion*> m_tokens;
326 mutable vector<Attribute*> m_attributes;
327 mutable multimap<string,const Attribute*> m_attributeIndex;
328 mutable vector<const char*> m_ids;
331 time_t m_expires,m_lastAccess;
335 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
337 return new SSCache(e);
341 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
343 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
346 void SHIBSP_API shibsp::registerSessionCaches()
348 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
359 void StoredSession::unmarshallAttributes() const
361 Attribute* attribute;
362 DDF attrs = m_obj["attributes"];
363 DDF attr = attrs.first();
364 while (!attr.isnull()) {
366 attribute = Attribute::unmarshall(attr);
367 m_attributes.push_back(attribute);
368 if (m_cache->m_log.isDebugEnabled())
369 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
370 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
372 catch (AttributeException& ex) {
373 const char* id = attr.first().name();
374 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
380 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
382 time_t now = time(nullptr);
386 if (now > m_expires) {
387 m_cache->m_log.info("session expired (ID: %s)", getID());
388 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
394 if (m_cache->m_log.isDebugEnabled())
395 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
396 if (!XMLString::equals(getClientAddress(),client_addr)) {
397 m_cache->m_log.warn("client address mismatch");
398 throw RetryableProfileException(
399 "Your IP address ($1) does not match the address recorded at the time the session was established.",
400 params(1,client_addr)
408 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
409 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
412 in.addmember("key").string(getID());
413 in.addmember("version").integer(m_obj["version"].integer());
414 in.addmember("application_id").string(app.getId());
416 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
417 #ifndef HAVE_GMTIME_R
418 struct tm* ptime=gmtime(timeout);
421 struct tm* ptime=gmtime_r(timeout,&res);
424 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
425 in.addmember("timeout").string(timebuf);
429 out=app.getServiceProvider().getListenerService()->send(in);
436 if (out.isstruct()) {
437 // We got an updated record back.
439 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
440 m_attributes.clear();
441 m_attributeIndex.clear();
448 if (!m_cache->m_storage)
449 throw ConfigurationException("Session touch requires a StorageService.");
451 // Do a versioned read.
454 int curver = m_obj["version"].integer();
455 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
457 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
458 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
461 // Adjust for expiration to recover last access time and check timeout.
462 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
463 lastAccess -= cacheTimeout;
464 if (*timeout > 0 && now - lastAccess >= *timeout) {
465 m_cache->m_log.info("session timed out (ID: %s)", getID());
466 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
469 // Update storage expiration, if possible.
471 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
473 catch (exception& ex) {
474 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
478 // We got an updated record back.
480 istringstream in(record);
483 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
484 m_attributes.clear();
485 m_attributeIndex.clear();
490 throw ConfigurationException("Session touch requires a StorageService.");
499 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
502 xmltooling::NDC ndc("addAttributes");
505 if (!m_cache->m_storage)
506 throw ConfigurationException("Session modification requires a StorageService.");
508 m_cache->m_log.debug("adding attributes to session (%s)", getID());
513 DDF attrs = m_obj["attributes"];
515 attrs = m_obj.addmember("attributes").list();
516 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
517 attr = (*a)->marshall();
521 // Tentatively increment the version.
522 m_obj["version"].integer(m_obj["version"].integer()+1);
526 string record(str.str());
529 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
532 // Roll back modification to record.
533 m_obj["version"].integer(m_obj["version"].integer()-1);
534 vector<Attribute*>::size_type count = attributes.size();
536 attrs.last().destroy();
541 // Roll back modification to record.
542 m_obj["version"].integer(m_obj["version"].integer()-1);
543 vector<Attribute*>::size_type count = attributes.size();
545 attrs.last().destroy();
548 // Fatal problem with update.
549 throw IOException("Unable to update stored session.");
553 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
554 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
556 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
557 throw IOException("Unable to read back stored session.");
562 istringstream in(record);
566 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
567 m_attributes.clear();
568 m_attributeIndex.clear();
569 newobj["version"].integer(ver);
575 } while (ver < 0); // negative indicates a sync issue so we retry
577 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
579 xlog->log.infoStream() <<
580 "Added the following attributes to session (ID: " <<
582 ") for (applicationId: " <<
583 m_obj["application_id"].string() <<
585 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
586 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
589 // We own them now, so clean them up.
590 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
593 const Assertion* StoredSession::getAssertion(const char* id) const
595 if (!m_cache->m_storage)
596 throw ConfigurationException("Assertion retrieval requires a StorageService.");
598 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
599 if (i!=m_tokens.end())
603 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
604 throw FatalProfileException("Assertion not found in cache.");
606 // Parse and bind the document into an XMLObject.
607 istringstream instr(tokenstr);
608 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
609 XercesJanitor<DOMDocument> janitor(doc);
610 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
613 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
615 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
617 // Transfer ownership to us.
623 void StoredSession::addAssertion(Assertion* assertion)
626 xmltooling::NDC ndc("addAssertion");
629 if (!m_cache->m_storage)
630 throw ConfigurationException("Session modification requires a StorageService.");
633 throw FatalProfileException("Unknown object type passed to session for storage.");
635 auto_ptr_char id(assertion->getID());
637 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
640 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
641 throw IOException("Unable to load expiration time for stored session.");
643 ostringstream tokenstr;
644 tokenstr << *assertion;
645 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
646 throw IOException("Attempted to insert duplicate assertion ID into session.");
650 DDF token = DDF(nullptr).string(id.get());
651 m_obj["assertions"].add(token);
653 // Tentatively increment the version.
654 m_obj["version"].integer(m_obj["version"].integer()+1);
658 string record(str.str());
661 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
665 m_obj["version"].integer(m_obj["version"].integer()-1);
666 m_cache->m_storage->deleteText(getID(), id.get());
672 m_obj["version"].integer(m_obj["version"].integer()-1);
675 // Fatal problem with update.
676 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
677 m_cache->m_storage->deleteText(getID(), id.get());
678 throw IOException("Unable to update stored session.");
682 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
683 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
685 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
686 m_cache->m_storage->deleteText(getID(), id.get());
687 throw IOException("Unable to read back stored session.");
692 istringstream in(record);
696 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
697 m_attributes.clear();
698 m_attributeIndex.clear();
699 newobj["version"].integer(ver);
705 } while (ver < 0); // negative indicates a sync issue so we retry
710 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
713 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
714 id.get(), m_obj["application_id"].string(), getID()
720 SessionCache::SessionCache()
724 SessionCache::~SessionCache()
728 SessionCacheEx::SessionCacheEx()
732 SessionCacheEx::~SessionCacheEx()
736 SSCache::SSCache(const DOMElement* e)
737 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
739 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
741 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
742 m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
744 SPConfig& conf = SPConfig::getConfig();
745 inproc = conf.isEnabled(SPConfig::InProcess);
747 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
748 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
749 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
750 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
751 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
752 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
753 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
754 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);
756 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
757 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
759 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
760 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
761 if (!m_inboundHeader.empty())
762 RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
763 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
766 if (conf.isEnabled(SPConfig::OutOfProcess)) {
767 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
769 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
771 m_log.info("bound to StorageService (%s)", ssid.c_str());
773 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
776 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
778 m_log.info("bound to arbitrary StorageService");
780 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
783 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
785 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
787 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
789 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
791 if (!m_storage_lite) {
792 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
793 m_storage_lite = m_storage;
796 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
800 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
802 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
803 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
804 m_lock = RWLock::create();
805 shutdown_wait = CondWait::create();
806 cleanup_thread = Thread::create(&cleanup_fn, this);
810 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
811 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
812 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
813 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
816 m_log.info("no ListenerService available, cache remoting disabled");
825 // Shut down the cleanup thread and let it know...
827 shutdown_wait->signal();
828 cleanup_thread->join(nullptr);
830 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
833 delete cleanup_thread;
834 delete shutdown_wait;
838 SPConfig& conf = SPConfig::getConfig();
839 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
840 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
841 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
842 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
843 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
853 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
854 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
855 m_storage->deleteString("SessionCacheTest", temp.get());
858 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
861 if (strlen(name) > 255) {
862 dup = string(name).substr(0,255);
867 DDFJanitor jobj(obj);
869 // Since we can't guarantee uniqueness, check for an existing record.
872 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
874 // Existing record, so we need to unmarshall it.
875 istringstream in(record);
880 obj = DDF(nullptr).structure();
883 if (!index || !*index)
885 DDF sessions = obj.addmember(index);
886 if (!sessions.islist())
888 DDF session = DDF(nullptr).string(key);
889 sessions.add(session);
891 // Remarshall the record.
895 // Try and store it back...
897 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
899 // Out of sync, or went missing, so retry.
900 return insert(key, expires, name, index);
903 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
904 // Hit a dup, so just retry, hopefully hitting the other branch.
905 return insert(key, expires, name, index);
909 void SSCache::insert(
910 const Application& app,
911 const HTTPRequest& httpRequest,
912 HTTPResponse& httpResponse,
914 const saml2md::EntityDescriptor* issuer,
915 const XMLCh* protocol,
916 const saml2::NameID* nameid,
917 const XMLCh* authn_instant,
918 const XMLCh* session_index,
919 const XMLCh* authncontext_class,
920 const XMLCh* authncontext_decl,
921 const vector<const Assertion*>* tokens,
922 const vector<Attribute*>* attributes
926 xmltooling::NDC ndc("insert");
929 throw ConfigurationException("SessionCache insertion requires a StorageService.");
931 m_log.debug("creating new session");
933 time_t now = time(nullptr);
934 auto_ptr_char index(session_index);
935 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
936 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
939 // Check for a pending logout.
941 strncpy(namebuf, name.get(), 255);
944 int ver = m_storage_lite->readText("Logout", namebuf, &pending);
947 DDFJanitor jpend(pendobj);
948 istringstream pstr(pending);
950 // IdP.SP.index contains logout expiration, if any.
951 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
952 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
953 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
954 logexpstr = deadmenwalking["_shibnull"].string();
956 auto_ptr_XMLCh dt(logexpstr);
957 DateTime dtobj(dt.get());
958 dtobj.parseDateTime();
959 time_t logexp = dtobj.getEpoch();
960 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
961 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
966 XMLCh* widekey = SAMLConfig::getConfig().generateIdentifier();
967 auto_ptr_char key(widekey);
968 XMLString::release(&widekey);
970 // Store session properties in DDF.
971 DDF obj = DDF(key.get()).structure();
972 DDFJanitor entryobj(obj);
973 obj.addmember("version").integer(1);
974 obj.addmember("application_id").string(app.getId());
976 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
977 #ifndef HAVE_GMTIME_R
978 struct tm* ptime=gmtime(&expires);
981 struct tm* ptime=gmtime_r(&expires,&res);
984 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
985 obj.addmember("expires").string(timebuf);
987 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
989 obj.addmember("entity_id").string(entity_id.get());
991 auto_ptr_char prot(protocol);
992 obj.addmember("protocol").string(prot.get());
995 auto_ptr_char instant(authn_instant);
996 obj.addmember("authn_instant").string(instant.get());
999 obj.addmember("session_index").string(index.get());
1000 if (authncontext_class) {
1001 auto_ptr_char ac(authncontext_class);
1002 obj.addmember("authncontext_class").string(ac.get());
1004 if (authncontext_decl) {
1005 auto_ptr_char ad(authncontext_decl);
1006 obj.addmember("authncontext_decl").string(ad.get());
1010 ostringstream namestr;
1012 obj.addmember("nameid").string(namestr.str().c_str());
1015 if (tokens && m_cacheAssertions) {
1016 obj.addmember("assertions").list();
1017 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1018 auto_ptr_char tokenid((*t)->getID());
1019 DDF tokid = DDF(nullptr).string(tokenid.get());
1020 obj["assertions"].add(tokid);
1026 DDF attrlist = obj.addmember("attributes").list();
1027 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1028 attr = (*a)->marshall();
1033 ostringstream record;
1036 m_log.debug("storing new session...");
1037 unsigned long cacheTimeout = getCacheTimeout(app);
1038 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1039 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1041 // Store the reverse mapping for logout.
1044 insert(key.get(), expires, name.get(), index.get());
1046 catch (exception& ex) {
1047 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1050 if (tokens && m_cacheAssertions) {
1052 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1053 ostringstream tokenstr;
1055 auto_ptr_char tokenid((*t)->getID());
1056 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1057 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1060 catch (exception& ex) {
1061 m_log.error("error storing assertion along with session: %s", ex.what());
1065 const char* pid = obj["entity_id"].string();
1066 const char* prot = obj["protocol"].string();
1067 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1068 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1070 // Transaction Logging
1071 string primaryAssertionID("none");
1072 if (m_cacheAssertions) {
1074 primaryAssertionID = obj["assertions"].first().string();
1077 auto_ptr_char tokenid(tokens->front()->getID());
1078 primaryAssertionID = tokenid.get();
1080 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1081 Locker locker(xlog);
1082 xlog->log.infoStream() <<
1083 "New session (ID: " <<
1085 ") with (applicationId: " <<
1087 ") for principal from (IdP: " <<
1088 (pid ? pid : "none") <<
1089 ") at (ClientAddress: " <<
1090 httpRequest.getRemoteAddr() <<
1091 ") with (NameIdentifier: " <<
1092 (nameid ? name.get() : "none") <<
1093 ") using (Protocol: " <<
1094 (prot ? prot : "none") <<
1095 ") from (AssertionID: " <<
1096 primaryAssertionID <<
1100 xlog->log.infoStream() <<
1101 "Cached the following attributes with session (ID: " <<
1103 ") for (applicationId: " <<
1106 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1107 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1108 xlog->log.info("}");
1111 if (!m_outboundHeader.empty())
1112 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1114 time_t cookieLifetime = 0;
1115 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1116 string k(key.get());
1117 k += shib_cookie.second;
1119 if (cookieLifetime > 0) {
1120 cookieLifetime += now;
1121 #ifndef HAVE_GMTIME_R
1122 ptime=gmtime(&cookieLifetime);
1124 ptime=gmtime_r(&cookieLifetime,&res);
1126 char cookietimebuf[64];
1127 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1131 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1134 bool SSCache::matches(
1135 const Application& app,
1136 const xmltooling::HTTPRequest& request,
1137 const saml2md::EntityDescriptor* issuer,
1138 const saml2::NameID& nameid,
1139 const set<string>* indexes
1142 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1144 Session* session = find(app, request);
1146 Locker locker(session, false);
1147 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1148 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1149 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1153 catch (exception& ex) {
1154 m_log.error("error while matching session: %s", ex.what());
1159 vector<string>::size_type SSCache::logout(
1160 const Application& app,
1161 const saml2md::EntityDescriptor* issuer,
1162 const saml2::NameID& nameid,
1163 const set<string>* indexes,
1165 vector<string>& sessionsKilled
1169 xmltooling::NDC ndc("logout");
1173 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1175 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1176 auto_ptr_char name(nameid.getName());
1178 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1180 if (strlen(name.get()) > 255)
1181 const_cast<char*>(name.get())[255] = 0;
1184 DDFJanitor jobj(obj);
1189 // Record the logout to prevent post-delivered assertions.
1190 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1191 #ifndef HAVE_GMTIME_R
1192 struct tm* ptime=gmtime(&expires);
1195 struct tm* ptime=gmtime_r(&expires,&res);
1198 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1201 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1203 istringstream lin(record);
1207 obj = DDF(nullptr).structure();
1210 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1211 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1213 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1214 root.addmember(x->c_str()).string(timebuf);
1217 root.addmember("_shibnull").string(timebuf);
1225 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1227 // Out of sync, or went missing, so retry.
1228 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1231 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1232 // Hit a dup, so just retry, hopefully hitting the other branch.
1233 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1240 // Read in potentially matching sessions.
1241 ver = m_storage_lite->readText("NameID", name.get(), &record);
1243 m_log.debug("no active sessions to logout for supplied issuer and subject");
1247 istringstream in(record);
1250 // The record contains child lists for each known session index.
1252 DDF sessions = obj.first();
1253 while (sessions.islist()) {
1254 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1255 key = sessions.first();
1256 while (key.isstring()) {
1257 // Fetch the session for comparison.
1258 Session* session = nullptr;
1260 session = find(app, key.string());
1262 catch (exception& ex) {
1263 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1267 Locker locker(session, false);
1269 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1271 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1272 sessionsKilled.push_back(key.string());
1276 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1280 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1284 // Session's gone, so...
1285 sessionsKilled.push_back(key.string());
1288 key = sessions.next();
1291 // No sessions left for this index?
1292 if (sessions.first().isnull())
1295 sessions = obj.next();
1298 if (obj.first().isnull())
1301 // If possible, write back the mapping record (this isn't crucial).
1304 m_storage_lite->deleteText("NameID", name.get());
1306 else if (!sessionsKilled.empty()) {
1309 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1310 m_log.warn("logout mapping record changed behind us, leaving it alone");
1313 catch (exception& ex) {
1314 m_log.error("error updating logout mapping record: %s", ex.what());
1317 return sessionsKilled.size();
1320 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1322 if (!XMLString::equals(n1.getName(), n2.getName()))
1325 const XMLCh* s1 = n1.getFormat();
1326 const XMLCh* s2 = n2.getFormat();
1328 s1 = saml2::NameID::UNSPECIFIED;
1330 s2 = saml2::NameID::UNSPECIFIED;
1331 if (!XMLString::equals(s1,s2))
1334 s1 = n1.getNameQualifier();
1335 s2 = n2.getNameQualifier();
1340 if (!XMLString::equals(s1,s2))
1343 s1 = n1.getSPNameQualifier();
1344 s2 = n2.getSPNameQualifier();
1349 if (!XMLString::equals(s1,s2))
1357 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1360 xmltooling::NDC ndc("find");
1362 StoredSession* session=nullptr;
1365 m_log.debug("searching local cache for session (%s)", key);
1367 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1368 if (i!=m_hashtable.end()) {
1369 // Save off and lock the session.
1370 session = i->second;
1373 m_log.debug("session found locally, validating it for use");
1381 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1382 m_log.debug("session not found locally, remoting the search");
1383 // Remote the request.
1384 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1387 in.addmember("key").string(key);
1388 in.addmember("application_id").string(app.getId());
1389 if (timeout && *timeout) {
1390 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1391 #ifndef HAVE_GMTIME_R
1392 struct tm* ptime=gmtime(timeout);
1395 struct tm* ptime=gmtime_r(timeout,&res);
1398 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1399 in.addmember("timeout").string(timebuf);
1403 out=app.getServiceProvider().getListenerService()->send(in);
1404 if (!out.isstruct()) {
1406 m_log.debug("session not found in remote cache");
1410 // Wrap the results in a local entry and save it.
1411 session = new StoredSession(this, out);
1412 // The remote end has handled timeout issues, we handle address and expiration checks.
1421 // We're out of process, so we can search the storage service directly.
1424 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1426 m_log.debug("searching for session (%s)", key);
1431 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1435 m_log.debug("reconstituting session and checking validity");
1437 istringstream in(record);
1440 unsigned long cacheTimeout = getCacheTimeout(app);
1441 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1442 time_t now=time(nullptr);
1444 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1445 m_log.info("session timed out (ID: %s)", key);
1447 const char* eid = obj["entity_id"].string();
1450 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1454 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1458 // Update storage expiration, if possible.
1460 m_storage->updateContext(key, now + cacheTimeout);
1462 catch (exception& ex) {
1463 m_log.error("failed to update session expiration: %s", ex.what());
1467 // Wrap the results in a local entry and save it.
1468 session = new StoredSession(this, obj);
1469 // We handled timeout issues, still need to handle address and expiration checks.
1472 throw ConfigurationException("SessionCache search requires a StorageService.");
1477 // Lock for writing and repeat the search to avoid duplication.
1479 SharedLock shared(m_lock, false);
1480 if (m_hashtable.count(key)) {
1481 // We're using an existing session entry.
1483 session = m_hashtable[key];
1487 m_hashtable[key]=session;
1493 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1494 m_log.error("an application (%s) tried to access another application's session", app.getId());
1499 // Verify currency and update the timestamp if indicated by caller.
1501 session->validate(app, client_addr, timeout);
1512 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1514 string id = active(app, request);
1518 Session* session = find(app, id.c_str(), client_addr, timeout);
1521 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1523 if (!m_outboundHeader.empty())
1524 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1525 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1526 string exp(shib_cookie.second);
1527 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1528 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1531 catch (exception&) {
1532 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1534 if (!m_outboundHeader.empty())
1535 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1536 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1537 string exp(shib_cookie.second);
1538 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1539 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1546 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1549 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1551 if (!m_inboundHeader.empty())
1552 session_id = request.getHeader(m_inboundHeader.c_str());
1553 if (session_id.empty()) {
1554 const char* c = request.getCookie(shib_cookie.first.c_str());
1559 if (!session_id.empty()) {
1561 if (!m_outboundHeader.empty())
1562 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1563 string exp(shib_cookie.second);
1564 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1565 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1567 remove(app, session_id.c_str());
1571 void SSCache::remove(const Application& app, const char* key)
1574 xmltooling::NDC ndc("remove");
1576 // Take care of local copy.
1580 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1581 // Remove the session from storage directly.
1583 m_storage->deleteContext(key);
1584 m_log.info("removed session (%s)", key);
1586 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1587 Locker locker(xlog);
1588 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1590 throw ConfigurationException("SessionCache removal requires a StorageService.");
1594 // Remote the request.
1595 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1598 in.addmember("key").string(key);
1599 in.addmember("application_id").string(app.getId());
1601 DDF out = app.getServiceProvider().getListenerService()->send(in);
1606 void SSCache::dormant(const char* key)
1609 xmltooling::NDC ndc("dormant");
1612 m_log.debug("deleting local copy of session (%s)", key);
1614 // lock the cache for writing, which means we know nobody is sitting in find()
1617 // grab the entry from the table
1618 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1619 if (i==m_hashtable.end()) {
1624 // ok, remove the entry and lock it
1625 StoredSession* entry=i->second;
1626 m_hashtable.erase(key);
1632 // we can release the cache entry lock because we know we're not in the cache anymore
1638 void* SSCache::cleanup_fn(void* p)
1641 xmltooling::NDC ndc("cleanup");
1644 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1647 // First, let's block all signals
1648 Thread::mask_all_signals();
1651 auto_ptr<Mutex> mutex(Mutex::create());
1653 // Load our configuration details...
1654 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1655 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1656 int rerun_timer = 900;
1658 rerun_timer = XMLString::parseInt(tag);
1659 if (rerun_timer <= 0)
1665 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1667 while (!pcache->shutdown) {
1668 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1669 if (pcache->shutdown)
1672 // Ok, let's run through the cleanup process and clean out
1673 // really old sessions. This is a two-pass process. The
1674 // first pass is done holding a read-lock while we iterate over
1675 // the cache. The second pass doesn't need a lock because
1676 // the 'deletes' will lock the cache.
1678 // Pass 1: iterate over the map and find all entries that have not been
1679 // used in the allotted timeout.
1680 vector<string> stale_keys;
1681 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1683 pcache->m_log.debug("cleanup thread running");
1685 pcache->m_lock->rdlock();
1686 for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1687 // If the last access was BEFORE the stale timeout...
1689 time_t last=i->second->getLastAccess();
1690 i->second->unlock();
1692 stale_keys.push_back(i->first);
1694 pcache->m_lock->unlock();
1696 if (!stale_keys.empty()) {
1697 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1699 // Pass 2: walk through the list of stale entries and remove them from the cache
1700 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1701 pcache->dormant(j->c_str());
1704 pcache->m_log.debug("cleanup thread completed");
1707 pcache->m_log.info("cleanup thread exiting");
1715 void SSCache::receive(DDF& in, ostream& out)
1718 xmltooling::NDC ndc("receive");
1720 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1722 throw ListenerException("Application not found, check configuration?");
1724 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1725 const char* key=in["key"].string();
1727 throw ListenerException("Required parameters missing for session lookup.");
1729 // Do an unversioned read.
1732 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1734 DDFJanitor jan(ret);
1739 // Adjust for expiration to recover last access time and check timeout.
1740 unsigned long cacheTimeout = getCacheTimeout(*app);
1741 lastAccess -= cacheTimeout;
1742 time_t now=time(nullptr);
1744 // See if we need to check for a timeout.
1745 if (in["timeout"].string()) {
1747 auto_ptr_XMLCh dt(in["timeout"].string());
1748 DateTime dtobj(dt.get());
1749 dtobj.parseDateTime();
1750 timeout = dtobj.getEpoch();
1752 if (timeout > 0 && now - lastAccess >= timeout) {
1753 m_log.info("session timed out (ID: %s)", key);
1755 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1758 // Update storage expiration, if possible.
1760 m_storage->updateContext(key, now + cacheTimeout);
1762 catch (exception& ex) {
1763 m_log.error("failed to update session expiration: %s", ex.what());
1767 // Send the record back.
1770 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1771 const char* key=in["key"].string();
1773 throw ListenerException("Required parameters missing for session check.");
1775 // Do a versioned read.
1778 int curver = in["version"].integer();
1779 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1781 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1782 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1785 // Adjust for expiration to recover last access time and check timeout.
1786 unsigned long cacheTimeout = getCacheTimeout(*app);
1787 lastAccess -= cacheTimeout;
1788 time_t now=time(nullptr);
1790 // See if we need to check for a timeout.
1792 auto_ptr_XMLCh dt(in["timeout"].string());
1794 DateTime dtobj(dt.get());
1795 dtobj.parseDateTime();
1796 timeout = dtobj.getEpoch();
1799 if (timeout > 0 && now - lastAccess >= timeout) {
1800 m_log.info("session timed out (ID: %s)", key);
1801 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1804 // Update storage expiration, if possible.
1806 m_storage->updateContext(key, now + cacheTimeout);
1808 catch (exception& ex) {
1809 m_log.error("failed to update session expiration: %s", ex.what());
1813 // Send the record back.
1818 DDFJanitor jan(ret);
1822 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1823 const char* key=in["key"].string();
1825 throw ListenerException("Required parameter missing for session removal.");
1829 DDFJanitor jan(ret);