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 or lifetime.
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 // As long as one of the two factors is set, add them together.
158 if (timeout.second > 0 || m_cacheAllowance > 0)
159 return timeout.second + m_cacheAllowance;
161 // If timeouts are off, and there's no cache slop set, then use the lifetime.
162 timeout = pair<bool,unsigned int>(false, 28800);
164 timeout = props->getUnsignedInt("lifetime");
165 if (!timeout.first || timeout.second == 0)
166 timeout.second = 28800;
168 return timeout.second;
174 StorageService* m_storage;
175 StorageService* m_storage_lite;
180 // maintain back-mappings of NameID/SessionIndex -> session key
181 void insert(const char* key, time_t expires, const char* name, const char* index);
182 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
184 bool m_cacheAssertions;
186 const DOMElement* m_root; // Only valid during initialization
187 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
188 string m_inboundHeader,m_outboundHeader;
190 // inproc means we buffer sessions in memory
192 map<string,StoredSession*> m_hashtable;
194 // management of buffered sessions
195 void dormant(const char* key);
196 static void* cleanup_fn(void*);
199 CondWait* shutdown_wait;
200 Thread* cleanup_thread;
203 class StoredSession : public virtual Session
206 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
210 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
211 auto_ptr_XMLCh exp(m_obj["expires"].string());
213 DateTime iso(exp.get());
215 m_expires = iso.getEpoch();
219 const char* nameid = obj["nameid"].string();
221 // Parse and bind the document into an XMLObject.
222 istringstream instr(nameid);
223 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
224 XercesJanitor<DOMDocument> janitor(doc);
225 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
226 n->unmarshall(doc->getDocumentElement(), true);
228 m_nameid = n.release();
232 m_lock = Mutex::create();
238 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
241 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
257 const char* getID() const {
260 const char* getApplicationID() const {
261 return m_obj["application_id"].string();
263 const char* getClientAddress() const {
264 return m_obj["client_addr"].string();
266 const char* getEntityID() const {
267 return m_obj["entity_id"].string();
269 const char* getProtocol() const {
270 return m_obj["protocol"].string();
272 const char* getAuthnInstant() const {
273 return m_obj["authn_instant"].string();
276 const saml2::NameID* getNameID() const {
280 const char* getSessionIndex() const {
281 return m_obj["session_index"].string();
283 const char* getAuthnContextClassRef() const {
284 return m_obj["authncontext_class"].string();
286 const char* getAuthnContextDeclRef() const {
287 return m_obj["authncontext_decl"].string();
289 const vector<Attribute*>& getAttributes() const {
290 if (m_attributes.empty())
291 unmarshallAttributes();
294 const multimap<string,const Attribute*>& getIndexedAttributes() const {
295 if (m_attributeIndex.empty()) {
296 if (m_attributes.empty())
297 unmarshallAttributes();
298 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
299 const vector<string>& aliases = (*a)->getAliases();
300 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
301 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
304 return m_attributeIndex;
306 const vector<const char*>& getAssertionIDs() const {
308 DDF ids = m_obj["assertions"];
309 DDF id = ids.first();
310 while (id.isstring()) {
311 m_ids.push_back(id.string());
318 void validate(const Application& application, const char* client_addr, time_t* timeout);
321 void addAttributes(const vector<Attribute*>& attributes);
322 const Assertion* getAssertion(const char* id) const;
323 void addAssertion(Assertion* assertion);
326 time_t getExpiration() const { return m_expires; }
327 time_t getLastAccess() const { return m_lastAccess; }
330 void unmarshallAttributes() const;
334 saml2::NameID* m_nameid;
335 mutable map<string,Assertion*> m_tokens;
337 mutable vector<Attribute*> m_attributes;
338 mutable multimap<string,const Attribute*> m_attributeIndex;
339 mutable vector<const char*> m_ids;
342 time_t m_expires,m_lastAccess;
346 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
348 return new SSCache(e);
352 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
354 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
357 void SHIBSP_API shibsp::registerSessionCaches()
359 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
370 void StoredSession::unmarshallAttributes() const
372 Attribute* attribute;
373 DDF attrs = m_obj["attributes"];
374 DDF attr = attrs.first();
375 while (!attr.isnull()) {
377 attribute = Attribute::unmarshall(attr);
378 m_attributes.push_back(attribute);
379 if (m_cache->m_log.isDebugEnabled())
380 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
381 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
383 catch (AttributeException& ex) {
384 const char* id = attr.first().name();
385 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
391 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
393 time_t now = time(nullptr);
397 if (now > m_expires) {
398 m_cache->m_log.info("session expired (ID: %s)", getID());
399 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
405 if (m_cache->m_log.isDebugEnabled())
406 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
407 if (!XMLString::equals(getClientAddress(),client_addr)) {
408 m_cache->m_log.warn("client address mismatch");
409 throw RetryableProfileException(
410 "Your IP address ($1) does not match the address recorded at the time the session was established.",
411 params(1,client_addr)
419 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
420 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
423 in.addmember("key").string(getID());
424 in.addmember("version").integer(m_obj["version"].integer());
425 in.addmember("application_id").string(app.getId());
427 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
428 #ifndef HAVE_GMTIME_R
429 struct tm* ptime=gmtime(timeout);
432 struct tm* ptime=gmtime_r(timeout,&res);
435 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
436 in.addmember("timeout").string(timebuf);
440 out=app.getServiceProvider().getListenerService()->send(in);
447 if (out.isstruct()) {
448 // We got an updated record back.
450 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
451 m_attributes.clear();
452 m_attributeIndex.clear();
459 if (!m_cache->m_storage)
460 throw ConfigurationException("Session touch requires a StorageService.");
462 // Do a versioned read.
465 int curver = m_obj["version"].integer();
466 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
468 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
469 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
472 // Adjust for expiration to recover last access time and check timeout.
473 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
474 lastAccess -= cacheTimeout;
475 if (*timeout > 0 && now - lastAccess >= *timeout) {
476 m_cache->m_log.info("session timed out (ID: %s)", getID());
477 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
480 // Update storage expiration, if possible.
482 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
484 catch (exception& ex) {
485 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
489 // We got an updated record back.
491 istringstream in(record);
494 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
495 m_attributes.clear();
496 m_attributeIndex.clear();
501 throw ConfigurationException("Session touch requires a StorageService.");
510 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
513 xmltooling::NDC ndc("addAttributes");
516 if (!m_cache->m_storage)
517 throw ConfigurationException("Session modification requires a StorageService.");
519 m_cache->m_log.debug("adding attributes to session (%s)", getID());
524 DDF attrs = m_obj["attributes"];
526 attrs = m_obj.addmember("attributes").list();
527 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
528 attr = (*a)->marshall();
532 // Tentatively increment the version.
533 m_obj["version"].integer(m_obj["version"].integer()+1);
537 string record(str.str());
540 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
543 // Roll back modification to record.
544 m_obj["version"].integer(m_obj["version"].integer()-1);
545 vector<Attribute*>::size_type count = attributes.size();
547 attrs.last().destroy();
552 // Roll back modification to record.
553 m_obj["version"].integer(m_obj["version"].integer()-1);
554 vector<Attribute*>::size_type count = attributes.size();
556 attrs.last().destroy();
559 // Fatal problem with update.
560 throw IOException("Unable to update stored session.");
564 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
565 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
567 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
568 throw IOException("Unable to read back stored session.");
573 istringstream in(record);
577 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
578 m_attributes.clear();
579 m_attributeIndex.clear();
580 newobj["version"].integer(ver);
586 } while (ver < 0); // negative indicates a sync issue so we retry
588 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
590 xlog->log.infoStream() <<
591 "Added the following attributes to session (ID: " <<
593 ") for (applicationId: " <<
594 m_obj["application_id"].string() <<
596 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
597 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
600 // We own them now, so clean them up.
601 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
604 const Assertion* StoredSession::getAssertion(const char* id) const
606 if (!m_cache->m_storage)
607 throw ConfigurationException("Assertion retrieval requires a StorageService.");
609 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
610 if (i!=m_tokens.end())
614 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
615 throw FatalProfileException("Assertion not found in cache.");
617 // Parse and bind the document into an XMLObject.
618 istringstream instr(tokenstr);
619 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
620 XercesJanitor<DOMDocument> janitor(doc);
621 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
624 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
626 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
628 // Transfer ownership to us.
634 void StoredSession::addAssertion(Assertion* assertion)
637 xmltooling::NDC ndc("addAssertion");
640 if (!m_cache->m_storage)
641 throw ConfigurationException("Session modification requires a StorageService.");
643 throw FatalProfileException("Unknown object type passed to session for storage.");
645 auto_ptr_char id(assertion->getID());
646 if (!id.get() || !*id.get())
647 throw IOException("Assertion did not carry an ID.");
648 else if (strlen(id.get()) > m_cache->m_storage->getCapabilities().getKeySize())
649 throw IOException("Assertion ID ($1) exceeds allowable storage key size.", params(1, id.get()));
651 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
654 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
655 throw IOException("Unable to load expiration time for stored session.");
657 ostringstream tokenstr;
658 tokenstr << *assertion;
659 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
660 throw IOException("Attempted to insert duplicate assertion ID into session.");
664 DDF token = DDF(nullptr).string(id.get());
665 m_obj["assertions"].add(token);
667 // Tentatively increment the version.
668 m_obj["version"].integer(m_obj["version"].integer()+1);
672 string record(str.str());
675 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
679 m_obj["version"].integer(m_obj["version"].integer()-1);
680 m_cache->m_storage->deleteText(getID(), id.get());
686 m_obj["version"].integer(m_obj["version"].integer()-1);
689 // Fatal problem with update.
690 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
691 m_cache->m_storage->deleteText(getID(), id.get());
692 throw IOException("Unable to update stored session.");
696 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
697 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
699 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
700 m_cache->m_storage->deleteText(getID(), id.get());
701 throw IOException("Unable to read back stored session.");
706 istringstream in(record);
710 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
711 m_attributes.clear();
712 m_attributeIndex.clear();
713 newobj["version"].integer(ver);
719 } while (ver < 0); // negative indicates a sync issue so we retry
724 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
727 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
728 id.get(), m_obj["application_id"].string(), getID()
734 SessionCache::SessionCache()
738 SessionCache::~SessionCache()
742 SessionCacheEx::SessionCacheEx()
746 SessionCacheEx::~SessionCacheEx()
750 SSCache::SSCache(const DOMElement* e)
751 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
753 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
755 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
756 m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
758 SPConfig& conf = SPConfig::getConfig();
759 inproc = conf.isEnabled(SPConfig::InProcess);
761 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
762 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
763 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
764 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
765 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
766 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
767 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
768 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);
770 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
771 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
773 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
774 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
775 if (!m_inboundHeader.empty())
776 RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
777 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
780 if (conf.isEnabled(SPConfig::OutOfProcess)) {
781 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
783 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
785 m_log.info("bound to StorageService (%s)", ssid.c_str());
787 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
790 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
792 m_log.info("bound to arbitrary StorageService");
794 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
797 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
799 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
801 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
803 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
805 if (!m_storage_lite) {
806 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
807 m_storage_lite = m_storage;
810 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
814 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
816 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
817 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
818 m_lock = RWLock::create();
819 shutdown_wait = CondWait::create();
820 cleanup_thread = Thread::create(&cleanup_fn, this);
824 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
825 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
826 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
827 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
830 m_log.info("no ListenerService available, cache remoting disabled");
839 // Shut down the cleanup thread and let it know...
841 shutdown_wait->signal();
842 cleanup_thread->join(nullptr);
844 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
847 delete cleanup_thread;
848 delete shutdown_wait;
852 SPConfig& conf = SPConfig::getConfig();
853 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
854 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
855 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
856 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
857 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
867 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
868 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
869 m_storage->deleteString("SessionCacheTest", temp.get());
872 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
875 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
876 if (strlen(name) > storageLimit) {
877 dup = string(name).substr(0, storageLimit);
882 DDFJanitor jobj(obj);
884 // Since we can't guarantee uniqueness, check for an existing record.
887 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
889 // Existing record, so we need to unmarshall it.
890 istringstream in(record);
895 obj = DDF(nullptr).structure();
898 if (!index || !*index)
900 DDF sessions = obj.addmember(index);
901 if (!sessions.islist())
903 DDF session = DDF(nullptr).string(key);
904 sessions.add(session);
906 // Remarshall the record.
910 // Try and store it back...
912 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
914 // Out of sync, or went missing, so retry.
915 return insert(key, expires, name, index);
918 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
919 // Hit a dup, so just retry, hopefully hitting the other branch.
920 return insert(key, expires, name, index);
924 void SSCache::insert(
925 const Application& app,
926 const HTTPRequest& httpRequest,
927 HTTPResponse& httpResponse,
929 const saml2md::EntityDescriptor* issuer,
930 const XMLCh* protocol,
931 const saml2::NameID* nameid,
932 const XMLCh* authn_instant,
933 const XMLCh* session_index,
934 const XMLCh* authncontext_class,
935 const XMLCh* authncontext_decl,
936 const vector<const Assertion*>* tokens,
937 const vector<Attribute*>* attributes
941 xmltooling::NDC ndc("insert");
944 throw ConfigurationException("SessionCache insertion requires a StorageService.");
946 m_log.debug("creating new session");
948 time_t now = time(nullptr);
949 auto_ptr_char index(session_index);
950 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
951 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
953 if (name.get() && *name.get()) {
954 // Check for a pending logout.
955 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
956 string namebuf = name.get();
957 if (namebuf.length() > storageLimit)
958 namebuf = namebuf.substr(0, storageLimit);
960 int ver = m_storage_lite->readText("Logout", namebuf.c_str(), &pending);
963 DDFJanitor jpend(pendobj);
964 istringstream pstr(pending);
966 // IdP.SP.index contains logout expiration, if any.
967 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
968 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
969 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
970 logexpstr = deadmenwalking["_shibnull"].string();
972 auto_ptr_XMLCh dt(logexpstr);
973 DateTime dtobj(dt.get());
974 dtobj.parseDateTime();
975 time_t logexp = dtobj.getEpoch();
976 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
977 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
982 XMLCh* widekey = SAMLConfig::getConfig().generateIdentifier();
983 auto_ptr_char key(widekey);
984 XMLString::release(&widekey);
986 // Store session properties in DDF.
987 DDF obj = DDF(key.get()).structure();
988 DDFJanitor entryobj(obj);
989 obj.addmember("version").integer(1);
990 obj.addmember("application_id").string(app.getId());
992 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
993 #ifndef HAVE_GMTIME_R
994 struct tm* ptime=gmtime(&expires);
997 struct tm* ptime=gmtime_r(&expires,&res);
1000 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1001 obj.addmember("expires").string(timebuf);
1003 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
1005 obj.addmember("entity_id").string(entity_id.get());
1007 auto_ptr_char prot(protocol);
1008 obj.addmember("protocol").string(prot.get());
1010 if (authn_instant) {
1011 auto_ptr_char instant(authn_instant);
1012 obj.addmember("authn_instant").string(instant.get());
1015 obj.addmember("session_index").string(index.get());
1016 if (authncontext_class) {
1017 auto_ptr_char ac(authncontext_class);
1018 obj.addmember("authncontext_class").string(ac.get());
1020 if (authncontext_decl) {
1021 auto_ptr_char ad(authncontext_decl);
1022 obj.addmember("authncontext_decl").string(ad.get());
1026 ostringstream namestr;
1028 obj.addmember("nameid").string(namestr.str().c_str());
1031 if (tokens && m_cacheAssertions) {
1032 obj.addmember("assertions").list();
1033 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1034 auto_ptr_char tokenid((*t)->getID());
1035 DDF tokid = DDF(nullptr).string(tokenid.get());
1036 obj["assertions"].add(tokid);
1042 DDF attrlist = obj.addmember("attributes").list();
1043 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1044 attr = (*a)->marshall();
1049 ostringstream record;
1052 m_log.debug("storing new session...");
1053 unsigned long cacheTimeout = getCacheTimeout(app);
1054 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1055 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1057 // Store the reverse mapping for logout.
1060 insert(key.get(), expires, name.get(), index.get());
1062 catch (exception& ex) {
1063 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1066 if (tokens && m_cacheAssertions) {
1068 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1069 ostringstream tokenstr;
1071 auto_ptr_char tokenid((*t)->getID());
1072 if (!tokenid.get() || !*tokenid.get() || strlen(tokenid.get()) > m_storage->getCapabilities().getKeySize())
1073 throw IOException("Assertion ID is missing or exceeds key size of storage service.");
1074 else if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1075 throw IOException("Duplicate assertion ID ($1)", params(1, tokenid.get()));
1078 catch (exception& ex) {
1079 m_log.error("error storing assertion along with session: %s", ex.what());
1083 const char* pid = obj["entity_id"].string();
1084 const char* prot = obj["protocol"].string();
1085 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1086 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1088 // Transaction Logging
1089 string primaryAssertionID("none");
1090 if (m_cacheAssertions) {
1092 primaryAssertionID = obj["assertions"].first().string();
1095 auto_ptr_char tokenid(tokens->front()->getID());
1096 primaryAssertionID = tokenid.get();
1098 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1099 Locker locker(xlog);
1100 xlog->log.infoStream() <<
1101 "New session (ID: " <<
1103 ") with (applicationId: " <<
1105 ") for principal from (IdP: " <<
1106 (pid ? pid : "none") <<
1107 ") at (ClientAddress: " <<
1108 httpRequest.getRemoteAddr() <<
1109 ") with (NameIdentifier: " <<
1110 (nameid ? name.get() : "none") <<
1111 ") using (Protocol: " <<
1112 (prot ? prot : "none") <<
1113 ") from (AssertionID: " <<
1114 primaryAssertionID <<
1118 xlog->log.infoStream() <<
1119 "Cached the following attributes with session (ID: " <<
1121 ") for (applicationId: " <<
1124 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1125 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1126 xlog->log.info("}");
1129 if (!m_outboundHeader.empty())
1130 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1132 time_t cookieLifetime = 0;
1133 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1134 string k(key.get());
1135 k += shib_cookie.second;
1137 if (cookieLifetime > 0) {
1138 cookieLifetime += now;
1139 #ifndef HAVE_GMTIME_R
1140 ptime=gmtime(&cookieLifetime);
1142 ptime=gmtime_r(&cookieLifetime,&res);
1144 char cookietimebuf[64];
1145 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1149 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1152 bool SSCache::matches(
1153 const Application& app,
1154 const xmltooling::HTTPRequest& request,
1155 const saml2md::EntityDescriptor* issuer,
1156 const saml2::NameID& nameid,
1157 const set<string>* indexes
1160 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1162 Session* session = find(app, request);
1164 Locker locker(session, false);
1165 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1166 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1167 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1171 catch (exception& ex) {
1172 m_log.error("error while matching session: %s", ex.what());
1177 vector<string>::size_type SSCache::logout(
1178 const Application& app,
1179 const saml2md::EntityDescriptor* issuer,
1180 const saml2::NameID& nameid,
1181 const set<string>* indexes,
1183 vector<string>& sessionsKilled
1187 xmltooling::NDC ndc("logout");
1191 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1193 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1194 auto_ptr_char name(nameid.getName());
1196 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1198 unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1199 if (strlen(name.get()) > storageLimit)
1200 const_cast<char*>(name.get())[storageLimit] = 0;
1203 DDFJanitor jobj(obj);
1208 // Record the logout to prevent post-delivered assertions.
1209 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1210 #ifndef HAVE_GMTIME_R
1211 struct tm* ptime=gmtime(&expires);
1214 struct tm* ptime=gmtime_r(&expires,&res);
1217 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1220 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1222 istringstream lin(record);
1226 obj = DDF(nullptr).structure();
1229 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1230 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1232 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1233 root.addmember(x->c_str()).string(timebuf);
1236 root.addmember("_shibnull").string(timebuf);
1244 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1246 // Out of sync, or went missing, so retry.
1247 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1250 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1251 // Hit a dup, so just retry, hopefully hitting the other branch.
1252 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1259 // Read in potentially matching sessions.
1260 ver = m_storage_lite->readText("NameID", name.get(), &record);
1262 m_log.debug("no active sessions to logout for supplied issuer and subject");
1266 istringstream in(record);
1269 // The record contains child lists for each known session index.
1271 DDF sessions = obj.first();
1272 while (sessions.islist()) {
1273 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1274 key = sessions.first();
1275 while (key.isstring()) {
1276 // Fetch the session for comparison.
1277 Session* session = nullptr;
1279 session = find(app, key.string());
1281 catch (exception& ex) {
1282 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1286 Locker locker(session, false);
1288 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1290 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1291 sessionsKilled.push_back(key.string());
1295 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1299 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1303 // Session's gone, so...
1304 sessionsKilled.push_back(key.string());
1307 key = sessions.next();
1310 // No sessions left for this index?
1311 if (sessions.first().isnull())
1314 sessions = obj.next();
1317 if (obj.first().isnull())
1320 // If possible, write back the mapping record (this isn't crucial).
1323 m_storage_lite->deleteText("NameID", name.get());
1325 else if (!sessionsKilled.empty()) {
1328 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1329 m_log.warn("logout mapping record changed behind us, leaving it alone");
1332 catch (exception& ex) {
1333 m_log.error("error updating logout mapping record: %s", ex.what());
1336 return sessionsKilled.size();
1339 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1341 if (!XMLString::equals(n1.getName(), n2.getName()))
1344 const XMLCh* s1 = n1.getFormat();
1345 const XMLCh* s2 = n2.getFormat();
1347 s1 = saml2::NameID::UNSPECIFIED;
1349 s2 = saml2::NameID::UNSPECIFIED;
1350 if (!XMLString::equals(s1,s2))
1353 s1 = n1.getNameQualifier();
1354 s2 = n2.getNameQualifier();
1359 if (!XMLString::equals(s1,s2))
1362 s1 = n1.getSPNameQualifier();
1363 s2 = n2.getSPNameQualifier();
1368 if (!XMLString::equals(s1,s2))
1376 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1379 xmltooling::NDC ndc("find");
1381 StoredSession* session=nullptr;
1384 m_log.debug("searching local cache for session (%s)", key);
1386 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1387 if (i!=m_hashtable.end()) {
1388 // Save off and lock the session.
1389 session = i->second;
1392 m_log.debug("session found locally, validating it for use");
1400 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1401 m_log.debug("session not found locally, remoting the search");
1402 // Remote the request.
1403 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1406 in.addmember("key").string(key);
1407 in.addmember("application_id").string(app.getId());
1408 if (timeout && *timeout) {
1409 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1410 #ifndef HAVE_GMTIME_R
1411 struct tm* ptime=gmtime(timeout);
1414 struct tm* ptime=gmtime_r(timeout,&res);
1417 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1418 in.addmember("timeout").string(timebuf);
1422 out=app.getServiceProvider().getListenerService()->send(in);
1423 if (!out.isstruct()) {
1425 m_log.debug("session not found in remote cache");
1429 // Wrap the results in a local entry and save it.
1430 session = new StoredSession(this, out);
1431 // The remote end has handled timeout issues, we handle address and expiration checks.
1440 // We're out of process, so we can search the storage service directly.
1443 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1445 m_log.debug("searching for session (%s)", key);
1450 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1454 m_log.debug("reconstituting session and checking validity");
1456 istringstream in(record);
1459 unsigned long cacheTimeout = getCacheTimeout(app);
1460 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1461 time_t now=time(nullptr);
1463 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1464 m_log.info("session timed out (ID: %s)", key);
1466 const char* eid = obj["entity_id"].string();
1469 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1473 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1477 // Update storage expiration, if possible.
1479 m_storage->updateContext(key, now + cacheTimeout);
1481 catch (exception& ex) {
1482 m_log.error("failed to update session expiration: %s", ex.what());
1486 // Wrap the results in a local entry and save it.
1487 session = new StoredSession(this, obj);
1488 // We handled timeout issues, still need to handle address and expiration checks.
1491 throw ConfigurationException("SessionCache search requires a StorageService.");
1496 // Lock for writing and repeat the search to avoid duplication.
1498 SharedLock shared(m_lock, false);
1499 if (m_hashtable.count(key)) {
1500 // We're using an existing session entry.
1502 session = m_hashtable[key];
1506 m_hashtable[key]=session;
1512 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1513 m_log.error("an application (%s) tried to access another application's session", app.getId());
1518 // Verify currency and update the timestamp if indicated by caller.
1520 session->validate(app, client_addr, timeout);
1531 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1533 string id = active(app, request);
1537 Session* session = find(app, id.c_str(), client_addr, timeout);
1540 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1542 if (!m_outboundHeader.empty())
1543 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1544 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1545 string exp(shib_cookie.second);
1546 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1547 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1550 catch (exception&) {
1551 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1553 if (!m_outboundHeader.empty())
1554 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1555 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1556 string exp(shib_cookie.second);
1557 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1558 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1565 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1568 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1570 if (!m_inboundHeader.empty())
1571 session_id = request.getHeader(m_inboundHeader.c_str());
1572 if (session_id.empty()) {
1573 const char* c = request.getCookie(shib_cookie.first.c_str());
1578 if (!session_id.empty()) {
1580 if (!m_outboundHeader.empty())
1581 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1582 string exp(shib_cookie.second);
1583 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1584 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1586 remove(app, session_id.c_str());
1590 void SSCache::remove(const Application& app, const char* key)
1593 xmltooling::NDC ndc("remove");
1595 // Take care of local copy.
1599 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1600 // Remove the session from storage directly.
1602 m_storage->deleteContext(key);
1603 m_log.info("removed session (%s)", key);
1605 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1606 Locker locker(xlog);
1607 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1609 throw ConfigurationException("SessionCache removal requires a StorageService.");
1613 // Remote the request.
1614 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1617 in.addmember("key").string(key);
1618 in.addmember("application_id").string(app.getId());
1620 DDF out = app.getServiceProvider().getListenerService()->send(in);
1625 void SSCache::dormant(const char* key)
1628 xmltooling::NDC ndc("dormant");
1631 m_log.debug("deleting local copy of session (%s)", key);
1633 // lock the cache for writing, which means we know nobody is sitting in find()
1636 // grab the entry from the table
1637 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1638 if (i==m_hashtable.end()) {
1643 // ok, remove the entry and lock it
1644 StoredSession* entry=i->second;
1645 m_hashtable.erase(key);
1651 // we can release the cache entry lock because we know we're not in the cache anymore
1657 void* SSCache::cleanup_fn(void* p)
1660 xmltooling::NDC ndc("cleanup");
1663 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1666 // First, let's block all signals
1667 Thread::mask_all_signals();
1670 auto_ptr<Mutex> mutex(Mutex::create());
1672 // Load our configuration details...
1673 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1674 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1675 int rerun_timer = 900;
1677 rerun_timer = XMLString::parseInt(tag);
1678 if (rerun_timer <= 0)
1684 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1686 while (!pcache->shutdown) {
1687 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1688 if (pcache->shutdown)
1691 // Ok, let's run through the cleanup process and clean out
1692 // really old sessions. This is a two-pass process. The
1693 // first pass is done holding a read-lock while we iterate over
1694 // the cache. The second pass doesn't need a lock because
1695 // the 'deletes' will lock the cache.
1697 // Pass 1: iterate over the map and find all entries that have not been
1698 // used in the allotted timeout.
1699 vector<string> stale_keys;
1700 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1702 pcache->m_log.debug("cleanup thread running");
1704 pcache->m_lock->rdlock();
1705 for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1706 // If the last access was BEFORE the stale timeout...
1708 time_t last=i->second->getLastAccess();
1709 i->second->unlock();
1711 stale_keys.push_back(i->first);
1713 pcache->m_lock->unlock();
1715 if (!stale_keys.empty()) {
1716 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1718 // Pass 2: walk through the list of stale entries and remove them from the cache
1719 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1720 pcache->dormant(j->c_str());
1723 pcache->m_log.debug("cleanup thread completed");
1726 pcache->m_log.info("cleanup thread exiting");
1734 void SSCache::receive(DDF& in, ostream& out)
1737 xmltooling::NDC ndc("receive");
1739 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1741 throw ListenerException("Application not found, check configuration?");
1743 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1744 const char* key=in["key"].string();
1746 throw ListenerException("Required parameters missing for session lookup.");
1748 // Do an unversioned read.
1751 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1753 DDFJanitor jan(ret);
1758 // Adjust for expiration to recover last access time and check timeout.
1759 unsigned long cacheTimeout = getCacheTimeout(*app);
1760 lastAccess -= cacheTimeout;
1761 time_t now=time(nullptr);
1763 // See if we need to check for a timeout.
1764 if (in["timeout"].string()) {
1766 auto_ptr_XMLCh dt(in["timeout"].string());
1767 DateTime dtobj(dt.get());
1768 dtobj.parseDateTime();
1769 timeout = dtobj.getEpoch();
1771 if (timeout > 0 && now - lastAccess >= timeout) {
1772 m_log.info("session timed out (ID: %s)", key);
1774 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1777 // Update storage expiration, if possible.
1779 m_storage->updateContext(key, now + cacheTimeout);
1781 catch (exception& ex) {
1782 m_log.error("failed to update session expiration: %s", ex.what());
1786 // Send the record back.
1789 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1790 const char* key=in["key"].string();
1792 throw ListenerException("Required parameters missing for session check.");
1794 // Do a versioned read.
1797 int curver = in["version"].integer();
1798 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1800 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1801 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1804 // Adjust for expiration to recover last access time and check timeout.
1805 unsigned long cacheTimeout = getCacheTimeout(*app);
1806 lastAccess -= cacheTimeout;
1807 time_t now=time(nullptr);
1809 // See if we need to check for a timeout.
1811 auto_ptr_XMLCh dt(in["timeout"].string());
1813 DateTime dtobj(dt.get());
1814 dtobj.parseDateTime();
1815 timeout = dtobj.getEpoch();
1818 if (timeout > 0 && now - lastAccess >= timeout) {
1819 m_log.info("session timed out (ID: %s)", key);
1820 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1823 // Update storage expiration, if possible.
1825 m_storage->updateContext(key, now + cacheTimeout);
1827 catch (exception& ex) {
1828 m_log.error("failed to update session expiration: %s", ex.what());
1832 // Send the record back.
1837 DDFJanitor jan(ret);
1841 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1842 const char* key=in["key"].string();
1844 throw ListenerException("Required parameter missing for session removal.");
1848 DDFJanitor jan(ret);