2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * StorageServiceSessionCache.cpp
20 * StorageService-based SessionCache implementation.
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
24 * layer their own cache plugin on top of this version either by delegating to it
25 * or using the remoting support. So this version will load sessions directly
26 * from the StorageService, instantiate enough to expose the Session API,
27 * and then delete everything when they're unlocked. All data in memory is always
28 * kept in sync with the StorageService (no lazy updates).
32 #include "Application.h"
33 #include "exceptions.h"
34 #include "ServiceProvider.h"
35 #include "SessionCacheEx.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "handler/RemotedHandler.h"
39 #include "remoting/ListenerService.h"
40 #include "util/SPConstants.h"
43 #include <xmltooling/io/HTTPRequest.h>
44 #include <xmltooling/io/HTTPResponse.h>
45 #include <xmltooling/util/DateTime.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/ParserPool.h>
48 #include <xmltooling/util/Threads.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
53 # include <saml/exceptions.h>
54 # include <saml/SAMLConfig.h>
55 # include <saml/saml2/core/Assertions.h>
56 # include <saml/saml2/metadata/Metadata.h>
57 # include <xmltooling/XMLToolingConfig.h>
58 # include <xmltooling/util/StorageService.h>
59 using namespace opensaml::saml2md;
62 # include <xmltooling/util/DateTime.h>
65 using namespace shibsp;
66 using namespace opensaml;
67 using namespace xmltooling;
73 class SSCache : public SessionCacheEx
75 ,public virtual Remoted
79 SSCache(const DOMElement* e);
83 void receive(DDF& in, ostream& out);
86 const Application& app,
87 const HTTPRequest& httpRequest,
88 HTTPResponse& httpResponse,
90 const saml2md::EntityDescriptor* issuer=nullptr,
91 const XMLCh* protocol=nullptr,
92 const saml2::NameID* nameid=nullptr,
93 const XMLCh* authn_instant=nullptr,
94 const XMLCh* session_index=nullptr,
95 const XMLCh* authncontext_class=nullptr,
96 const XMLCh* authncontext_decl=nullptr,
97 const vector<const Assertion*>* tokens=nullptr,
98 const vector<Attribute*>* attributes=nullptr
100 vector<string>::size_type logout(
101 const Application& app,
102 const saml2md::EntityDescriptor* issuer,
103 const saml2::NameID& nameid,
104 const set<string>* indexes,
106 vector<string>& sessions
109 const Application& app,
110 const HTTPRequest& request,
111 const saml2md::EntityDescriptor* issuer,
112 const saml2::NameID& nameid,
113 const set<string>* indexes
116 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
117 void remove(const Application& app, const char* key);
120 string active(const Application& app, const HTTPRequest& request) {
121 if (!m_inboundHeader.empty()) {
122 string session_id = request.getHeader(m_inboundHeader.c_str());
123 if (!session_id.empty())
126 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
127 const char* session_id = request.getCookie(shib_cookie.first.c_str());
128 return (session_id ? session_id : "");
131 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
132 string id = active(app, request);
134 return find(app, id.c_str(), client_addr, timeout);
138 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
139 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
141 unsigned long getCacheTimeout(const Application& app) {
142 // Computes offset for adjusting expiration of sessions.
143 // This can either be static, or dynamic based on the per-app session timeout.
145 return m_cacheTimeout;
146 pair<bool,unsigned int> timeout;
147 const PropertySet* props = app.getPropertySet("Sessions");
149 timeout = props->getUnsignedInt("timeout");
151 timeout.second = 3600;
153 return timeout.second + m_cacheAllowance;
159 StorageService* m_storage;
160 StorageService* m_storage_lite;
165 // maintain back-mappings of NameID/SessionIndex -> session key
166 void insert(const char* key, time_t expires, const char* name, const char* index);
167 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
169 bool m_cacheAssertions;
171 const DOMElement* m_root; // Only valid during initialization
172 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
173 string m_inboundHeader,m_outboundHeader;
175 // inproc means we buffer sessions in memory
177 map<string,StoredSession*> m_hashtable;
179 // management of buffered sessions
180 void dormant(const char* key);
181 static void* cleanup_fn(void*);
184 CondWait* shutdown_wait;
185 Thread* cleanup_thread;
188 class StoredSession : public virtual Session
191 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
195 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
196 auto_ptr_XMLCh exp(m_obj["expires"].string());
198 DateTime iso(exp.get());
200 m_expires = iso.getEpoch();
204 const char* nameid = obj["nameid"].string();
206 // Parse and bind the document into an XMLObject.
207 istringstream instr(nameid);
208 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
209 XercesJanitor<DOMDocument> janitor(doc);
210 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
211 n->unmarshall(doc->getDocumentElement(), true);
213 m_nameid = n.release();
217 m_lock = Mutex::create();
223 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
226 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
242 const char* getID() const {
245 const char* getApplicationID() const {
246 return m_obj["application_id"].string();
248 const char* getClientAddress() const {
249 return m_obj["client_addr"].string();
251 const char* getEntityID() const {
252 return m_obj["entity_id"].string();
254 const char* getProtocol() const {
255 return m_obj["protocol"].string();
257 const char* getAuthnInstant() const {
258 return m_obj["authn_instant"].string();
261 const saml2::NameID* getNameID() const {
265 const char* getSessionIndex() const {
266 return m_obj["session_index"].string();
268 const char* getAuthnContextClassRef() const {
269 return m_obj["authncontext_class"].string();
271 const char* getAuthnContextDeclRef() const {
272 return m_obj["authncontext_decl"].string();
274 const vector<Attribute*>& getAttributes() const {
275 if (m_attributes.empty())
276 unmarshallAttributes();
279 const multimap<string,const Attribute*>& getIndexedAttributes() const {
280 if (m_attributeIndex.empty()) {
281 if (m_attributes.empty())
282 unmarshallAttributes();
283 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
284 const vector<string>& aliases = (*a)->getAliases();
285 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
286 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
289 return m_attributeIndex;
291 const vector<const char*>& getAssertionIDs() const {
293 DDF ids = m_obj["assertions"];
294 DDF id = ids.first();
295 while (id.isstring()) {
296 m_ids.push_back(id.string());
303 void validate(const Application& application, const char* client_addr, time_t* timeout);
306 void addAttributes(const vector<Attribute*>& attributes);
307 const Assertion* getAssertion(const char* id) const;
308 void addAssertion(Assertion* assertion);
311 time_t getExpiration() const { return m_expires; }
312 time_t getLastAccess() const { return m_lastAccess; }
315 void unmarshallAttributes() const;
319 saml2::NameID* m_nameid;
320 mutable map<string,Assertion*> m_tokens;
322 mutable vector<Attribute*> m_attributes;
323 mutable multimap<string,const Attribute*> m_attributeIndex;
324 mutable vector<const char*> m_ids;
327 time_t m_expires,m_lastAccess;
331 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
333 return new SSCache(e);
337 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
339 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
342 void SHIBSP_API shibsp::registerSessionCaches()
344 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
355 void StoredSession::unmarshallAttributes() const
357 Attribute* attribute;
358 DDF attrs = m_obj["attributes"];
359 DDF attr = attrs.first();
360 while (!attr.isnull()) {
362 attribute = Attribute::unmarshall(attr);
363 m_attributes.push_back(attribute);
364 if (m_cache->m_log.isDebugEnabled())
365 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
366 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
368 catch (AttributeException& ex) {
369 const char* id = attr.first().name();
370 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
376 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
378 time_t now = time(nullptr);
382 if (now > m_expires) {
383 m_cache->m_log.info("session expired (ID: %s)", getID());
384 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
390 if (m_cache->m_log.isDebugEnabled())
391 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
392 if (!XMLString::equals(getClientAddress(),client_addr)) {
393 m_cache->m_log.warn("client address mismatch");
394 throw RetryableProfileException(
395 "Your IP address ($1) does not match the address recorded at the time the session was established.",
396 params(1,client_addr)
404 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
405 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
408 in.addmember("key").string(getID());
409 in.addmember("version").integer(m_obj["version"].integer());
411 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
412 #ifndef HAVE_GMTIME_R
413 struct tm* ptime=gmtime(timeout);
416 struct tm* ptime=gmtime_r(timeout,&res);
419 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
420 in.addmember("timeout").string(timebuf);
424 out=app.getServiceProvider().getListenerService()->send(in);
431 if (out.isstruct()) {
432 // We got an updated record back.
434 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
435 m_attributes.clear();
436 m_attributeIndex.clear();
443 if (!m_cache->m_storage)
444 throw ConfigurationException("Session touch requires a StorageService.");
446 // Do a versioned read.
449 int curver = m_obj["version"].integer();
450 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
452 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
453 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
456 // Adjust for expiration to recover last access time and check timeout.
457 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
458 lastAccess -= cacheTimeout;
459 if (*timeout > 0 && now - lastAccess >= *timeout) {
460 m_cache->m_log.info("session timed out (ID: %s)", getID());
461 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
464 // Update storage expiration, if possible.
466 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
468 catch (exception& ex) {
469 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
473 // We got an updated record back.
475 istringstream in(record);
478 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
479 m_attributes.clear();
480 m_attributeIndex.clear();
485 throw ConfigurationException("Session touch requires a StorageService.");
494 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
497 xmltooling::NDC ndc("addAttributes");
500 if (!m_cache->m_storage)
501 throw ConfigurationException("Session modification requires a StorageService.");
503 m_cache->m_log.debug("adding attributes to session (%s)", getID());
508 DDF attrs = m_obj["attributes"];
510 attrs = m_obj.addmember("attributes").list();
511 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
512 attr = (*a)->marshall();
516 // Tentatively increment the version.
517 m_obj["version"].integer(m_obj["version"].integer()+1);
521 string record(str.str());
524 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
527 // Roll back modification to record.
528 m_obj["version"].integer(m_obj["version"].integer()-1);
529 vector<Attribute*>::size_type count = attributes.size();
531 attrs.last().destroy();
536 // Roll back modification to record.
537 m_obj["version"].integer(m_obj["version"].integer()-1);
538 vector<Attribute*>::size_type count = attributes.size();
540 attrs.last().destroy();
543 // Fatal problem with update.
544 throw IOException("Unable to update stored session.");
548 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
549 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
551 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
552 throw IOException("Unable to read back stored session.");
557 istringstream in(record);
561 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
562 m_attributes.clear();
563 m_attributeIndex.clear();
564 newobj["version"].integer(ver);
570 } while (ver < 0); // negative indicates a sync issue so we retry
572 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
574 xlog->log.infoStream() <<
575 "Added the following attributes to session (ID: " <<
577 ") for (applicationId: " <<
578 m_obj["application_id"].string() <<
580 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
581 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
584 // We own them now, so clean them up.
585 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
588 const Assertion* StoredSession::getAssertion(const char* id) const
590 if (!m_cache->m_storage)
591 throw ConfigurationException("Assertion retrieval requires a StorageService.");
593 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
594 if (i!=m_tokens.end())
598 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
599 throw FatalProfileException("Assertion not found in cache.");
601 // Parse and bind the document into an XMLObject.
602 istringstream instr(tokenstr);
603 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
604 XercesJanitor<DOMDocument> janitor(doc);
605 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
608 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
610 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
612 // Transfer ownership to us.
618 void StoredSession::addAssertion(Assertion* assertion)
621 xmltooling::NDC ndc("addAssertion");
624 if (!m_cache->m_storage)
625 throw ConfigurationException("Session modification requires a StorageService.");
628 throw FatalProfileException("Unknown object type passed to session for storage.");
630 auto_ptr_char id(assertion->getID());
632 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
635 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
636 throw IOException("Unable to load expiration time for stored session.");
638 ostringstream tokenstr;
639 tokenstr << *assertion;
640 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
641 throw IOException("Attempted to insert duplicate assertion ID into session.");
645 DDF token = DDF(nullptr).string(id.get());
646 m_obj["assertions"].add(token);
648 // Tentatively increment the version.
649 m_obj["version"].integer(m_obj["version"].integer()+1);
653 string record(str.str());
656 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
660 m_obj["version"].integer(m_obj["version"].integer()-1);
661 m_cache->m_storage->deleteText(getID(), id.get());
667 m_obj["version"].integer(m_obj["version"].integer()-1);
670 // Fatal problem with update.
671 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
672 m_cache->m_storage->deleteText(getID(), id.get());
673 throw IOException("Unable to update stored session.");
677 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
678 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
680 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
681 m_cache->m_storage->deleteText(getID(), id.get());
682 throw IOException("Unable to read back stored session.");
687 istringstream in(record);
691 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
692 m_attributes.clear();
693 m_attributeIndex.clear();
694 newobj["version"].integer(ver);
700 } while (ver < 0); // negative indicates a sync issue so we retry
705 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
708 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
709 id.get(), m_obj["application_id"].string(), getID()
715 SessionCache::SessionCache()
719 SessionCache::~SessionCache()
723 SessionCacheEx::SessionCacheEx()
727 SessionCacheEx::~SessionCacheEx()
731 SSCache::SSCache(const DOMElement* e)
732 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
734 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
736 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
737 m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
739 SPConfig& conf = SPConfig::getConfig();
740 inproc = conf.isEnabled(SPConfig::InProcess);
742 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
743 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
744 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
745 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
746 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
747 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
748 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
749 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);
751 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
752 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
754 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
755 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
756 if (!m_inboundHeader.empty())
757 RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
758 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
761 if (conf.isEnabled(SPConfig::OutOfProcess)) {
762 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
764 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
766 m_log.info("bound to StorageService (%s)", ssid.c_str());
768 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
771 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
773 m_log.info("bound to arbitrary StorageService");
775 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
778 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
780 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
782 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
784 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
786 if (!m_storage_lite) {
787 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
788 m_storage_lite = m_storage;
791 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
795 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
797 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
798 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
799 m_lock = RWLock::create();
800 shutdown_wait = CondWait::create();
801 cleanup_thread = Thread::create(&cleanup_fn, this);
805 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
806 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
807 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
808 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
811 m_log.info("no ListenerService available, cache remoting disabled");
820 // Shut down the cleanup thread and let it know...
822 shutdown_wait->signal();
823 cleanup_thread->join(nullptr);
825 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
828 delete cleanup_thread;
829 delete shutdown_wait;
833 SPConfig& conf = SPConfig::getConfig();
834 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
835 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
836 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
837 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
838 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
848 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
849 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
850 m_storage->deleteString("SessionCacheTest", temp.get());
853 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
856 if (strlen(name) > 255) {
857 dup = string(name).substr(0,255);
862 DDFJanitor jobj(obj);
864 // Since we can't guarantee uniqueness, check for an existing record.
867 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
869 // Existing record, so we need to unmarshall it.
870 istringstream in(record);
875 obj = DDF(nullptr).structure();
878 if (!index || !*index)
880 DDF sessions = obj.addmember(index);
881 if (!sessions.islist())
883 DDF session = DDF(nullptr).string(key);
884 sessions.add(session);
886 // Remarshall the record.
890 // Try and store it back...
892 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
894 // Out of sync, or went missing, so retry.
895 return insert(key, expires, name, index);
898 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
899 // Hit a dup, so just retry, hopefully hitting the other branch.
900 return insert(key, expires, name, index);
904 void SSCache::insert(
905 const Application& app,
906 const HTTPRequest& httpRequest,
907 HTTPResponse& httpResponse,
909 const saml2md::EntityDescriptor* issuer,
910 const XMLCh* protocol,
911 const saml2::NameID* nameid,
912 const XMLCh* authn_instant,
913 const XMLCh* session_index,
914 const XMLCh* authncontext_class,
915 const XMLCh* authncontext_decl,
916 const vector<const Assertion*>* tokens,
917 const vector<Attribute*>* attributes
921 xmltooling::NDC ndc("insert");
924 throw ConfigurationException("SessionCache insertion requires a StorageService.");
926 m_log.debug("creating new session");
928 time_t now = time(nullptr);
929 auto_ptr_char index(session_index);
930 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
931 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
934 // Check for a pending logout.
936 strncpy(namebuf, name.get(), 255);
939 int ver = m_storage_lite->readText("Logout", namebuf, &pending);
942 DDFJanitor jpend(pendobj);
943 istringstream pstr(pending);
945 // IdP.SP.index contains logout expiration, if any.
946 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
947 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
948 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
949 logexpstr = deadmenwalking["_shibnull"].string();
951 auto_ptr_XMLCh dt(logexpstr);
952 DateTime dtobj(dt.get());
953 dtobj.parseDateTime();
954 time_t logexp = dtobj.getEpoch();
955 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
956 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
961 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
963 // Store session properties in DDF.
964 DDF obj = DDF(key.get()).structure();
965 DDFJanitor entryobj(obj);
966 obj.addmember("version").integer(1);
967 obj.addmember("application_id").string(app.getId());
969 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
970 #ifndef HAVE_GMTIME_R
971 struct tm* ptime=gmtime(&expires);
974 struct tm* ptime=gmtime_r(&expires,&res);
977 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
978 obj.addmember("expires").string(timebuf);
980 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
982 obj.addmember("entity_id").string(entity_id.get());
984 auto_ptr_char prot(protocol);
985 obj.addmember("protocol").string(prot.get());
988 auto_ptr_char instant(authn_instant);
989 obj.addmember("authn_instant").string(instant.get());
992 obj.addmember("session_index").string(index.get());
993 if (authncontext_class) {
994 auto_ptr_char ac(authncontext_class);
995 obj.addmember("authncontext_class").string(ac.get());
997 if (authncontext_decl) {
998 auto_ptr_char ad(authncontext_decl);
999 obj.addmember("authncontext_decl").string(ad.get());
1003 ostringstream namestr;
1005 obj.addmember("nameid").string(namestr.str().c_str());
1008 if (tokens && m_cacheAssertions) {
1009 obj.addmember("assertions").list();
1010 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1011 auto_ptr_char tokenid((*t)->getID());
1012 DDF tokid = DDF(nullptr).string(tokenid.get());
1013 obj["assertions"].add(tokid);
1019 DDF attrlist = obj.addmember("attributes").list();
1020 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1021 attr = (*a)->marshall();
1026 ostringstream record;
1029 m_log.debug("storing new session...");
1030 unsigned long cacheTimeout = getCacheTimeout(app);
1031 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1032 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1034 // Store the reverse mapping for logout.
1037 insert(key.get(), expires, name.get(), index.get());
1039 catch (exception& ex) {
1040 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1043 if (tokens && m_cacheAssertions) {
1045 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1046 ostringstream tokenstr;
1048 auto_ptr_char tokenid((*t)->getID());
1049 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1050 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1053 catch (exception& ex) {
1054 m_log.error("error storing assertion along with session: %s", ex.what());
1058 const char* pid = obj["entity_id"].string();
1059 const char* prot = obj["protocol"].string();
1060 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1061 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1063 // Transaction Logging
1064 string primaryAssertionID("none");
1065 if (m_cacheAssertions) {
1067 primaryAssertionID = obj["assertions"].first().string();
1070 auto_ptr_char tokenid(tokens->front()->getID());
1071 primaryAssertionID = tokenid.get();
1073 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1074 Locker locker(xlog);
1075 xlog->log.infoStream() <<
1076 "New session (ID: " <<
1078 ") with (applicationId: " <<
1080 ") for principal from (IdP: " <<
1081 (pid ? pid : "none") <<
1082 ") at (ClientAddress: " <<
1083 httpRequest.getRemoteAddr() <<
1084 ") with (NameIdentifier: " <<
1085 (nameid ? name.get() : "none") <<
1086 ") using (Protocol: " <<
1087 (prot ? prot : "none") <<
1088 ") from (AssertionID: " <<
1089 primaryAssertionID <<
1093 xlog->log.infoStream() <<
1094 "Cached the following attributes with session (ID: " <<
1096 ") for (applicationId: " <<
1099 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1100 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1101 xlog->log.info("}");
1104 if (!m_outboundHeader.empty())
1105 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1107 time_t cookieLifetime = 0;
1108 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1109 string k(key.get());
1110 k += shib_cookie.second;
1112 if (cookieLifetime > 0) {
1113 cookieLifetime += now;
1114 #ifndef HAVE_GMTIME_R
1115 ptime=gmtime(&cookieLifetime);
1117 ptime=gmtime_r(&cookieLifetime,&res);
1119 char cookietimebuf[64];
1120 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1124 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1127 bool SSCache::matches(
1128 const Application& app,
1129 const xmltooling::HTTPRequest& request,
1130 const saml2md::EntityDescriptor* issuer,
1131 const saml2::NameID& nameid,
1132 const set<string>* indexes
1135 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1137 Session* session = find(app, request);
1139 Locker locker(session, false);
1140 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1141 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1142 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1146 catch (exception& ex) {
1147 m_log.error("error while matching session: %s", ex.what());
1152 vector<string>::size_type SSCache::logout(
1153 const Application& app,
1154 const saml2md::EntityDescriptor* issuer,
1155 const saml2::NameID& nameid,
1156 const set<string>* indexes,
1158 vector<string>& sessionsKilled
1162 xmltooling::NDC ndc("logout");
1166 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1168 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1169 auto_ptr_char name(nameid.getName());
1171 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1173 if (strlen(name.get()) > 255)
1174 const_cast<char*>(name.get())[255] = 0;
1177 DDFJanitor jobj(obj);
1182 // Record the logout to prevent post-delivered assertions.
1183 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1184 #ifndef HAVE_GMTIME_R
1185 struct tm* ptime=gmtime(&expires);
1188 struct tm* ptime=gmtime_r(&expires,&res);
1191 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1194 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1196 istringstream lin(record);
1200 obj = DDF(nullptr).structure();
1203 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1204 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1206 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1207 root.addmember(x->c_str()).string(timebuf);
1210 root.addmember("_shibnull").string(timebuf);
1218 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1220 // Out of sync, or went missing, so retry.
1221 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1224 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1225 // Hit a dup, so just retry, hopefully hitting the other branch.
1226 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1233 // Read in potentially matching sessions.
1234 ver = m_storage_lite->readText("NameID", name.get(), &record);
1236 m_log.debug("no active sessions to logout for supplied issuer and subject");
1240 istringstream in(record);
1243 // The record contains child lists for each known session index.
1245 DDF sessions = obj.first();
1246 while (sessions.islist()) {
1247 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1248 key = sessions.first();
1249 while (key.isstring()) {
1250 // Fetch the session for comparison.
1251 Session* session = nullptr;
1253 session = find(app, key.string());
1255 catch (exception& ex) {
1256 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1260 Locker locker(session, false);
1262 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1264 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1265 sessionsKilled.push_back(key.string());
1269 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1273 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1277 // Session's gone, so...
1278 sessionsKilled.push_back(key.string());
1281 key = sessions.next();
1284 // No sessions left for this index?
1285 if (sessions.first().isnull())
1288 sessions = obj.next();
1291 if (obj.first().isnull())
1294 // If possible, write back the mapping record (this isn't crucial).
1297 m_storage_lite->deleteText("NameID", name.get());
1299 else if (!sessionsKilled.empty()) {
1302 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1303 m_log.warn("logout mapping record changed behind us, leaving it alone");
1306 catch (exception& ex) {
1307 m_log.error("error updating logout mapping record: %s", ex.what());
1310 return sessionsKilled.size();
1313 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1315 if (!XMLString::equals(n1.getName(), n2.getName()))
1318 const XMLCh* s1 = n1.getFormat();
1319 const XMLCh* s2 = n2.getFormat();
1321 s1 = saml2::NameID::UNSPECIFIED;
1323 s2 = saml2::NameID::UNSPECIFIED;
1324 if (!XMLString::equals(s1,s2))
1327 s1 = n1.getNameQualifier();
1328 s2 = n2.getNameQualifier();
1333 if (!XMLString::equals(s1,s2))
1336 s1 = n1.getSPNameQualifier();
1337 s2 = n2.getSPNameQualifier();
1342 if (!XMLString::equals(s1,s2))
1350 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1353 xmltooling::NDC ndc("find");
1355 StoredSession* session=nullptr;
1358 m_log.debug("searching local cache for session (%s)", key);
1360 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1361 if (i!=m_hashtable.end()) {
1362 // Save off and lock the session.
1363 session = i->second;
1366 m_log.debug("session found locally, validating it for use");
1374 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1375 m_log.debug("session not found locally, remoting the search");
1376 // Remote the request.
1377 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1380 in.addmember("key").string(key);
1381 in.addmember("application_id").string(app.getId());
1382 if (timeout && *timeout) {
1383 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1384 #ifndef HAVE_GMTIME_R
1385 struct tm* ptime=gmtime(timeout);
1388 struct tm* ptime=gmtime_r(timeout,&res);
1391 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1392 in.addmember("timeout").string(timebuf);
1396 out=app.getServiceProvider().getListenerService()->send(in);
1397 if (!out.isstruct()) {
1399 m_log.debug("session not found in remote cache");
1403 // Wrap the results in a local entry and save it.
1404 session = new StoredSession(this, out);
1405 // The remote end has handled timeout issues, we handle address and expiration checks.
1414 // We're out of process, so we can search the storage service directly.
1417 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1419 m_log.debug("searching for session (%s)", key);
1424 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1428 m_log.debug("reconstituting session and checking validity");
1430 istringstream in(record);
1433 unsigned long cacheTimeout = getCacheTimeout(app);
1434 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1435 time_t now=time(nullptr);
1437 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1438 m_log.info("session timed out (ID: %s)", key);
1440 const char* eid = obj["entity_id"].string();
1443 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1447 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1451 // Update storage expiration, if possible.
1453 m_storage->updateContext(key, now + cacheTimeout);
1455 catch (exception& ex) {
1456 m_log.error("failed to update session expiration: %s", ex.what());
1460 // Wrap the results in a local entry and save it.
1461 session = new StoredSession(this, obj);
1462 // We handled timeout issues, still need to handle address and expiration checks.
1465 throw ConfigurationException("SessionCache search requires a StorageService.");
1470 // Lock for writing and repeat the search to avoid duplication.
1472 SharedLock shared(m_lock, false);
1473 if (m_hashtable.count(key)) {
1474 // We're using an existing session entry.
1476 session = m_hashtable[key];
1480 m_hashtable[key]=session;
1486 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1487 m_log.error("an application (%s) tried to access another application's session", app.getId());
1492 // Verify currency and update the timestamp if indicated by caller.
1494 session->validate(app, client_addr, timeout);
1505 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1507 string id = active(app, request);
1511 Session* session = find(app, id.c_str(), client_addr, timeout);
1514 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1516 if (!m_outboundHeader.empty())
1517 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1518 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1519 string exp(shib_cookie.second);
1520 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1521 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1524 catch (exception&) {
1525 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1527 if (!m_outboundHeader.empty())
1528 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1529 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1530 string exp(shib_cookie.second);
1531 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1532 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1539 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1542 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1544 if (!m_inboundHeader.empty())
1545 session_id = request.getHeader(m_inboundHeader.c_str());
1546 if (session_id.empty()) {
1547 const char* c = request.getCookie(shib_cookie.first.c_str());
1552 if (!session_id.empty()) {
1554 if (!m_outboundHeader.empty())
1555 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
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());
1560 remove(app, session_id.c_str());
1564 void SSCache::remove(const Application& app, const char* key)
1567 xmltooling::NDC ndc("remove");
1569 // Take care of local copy.
1573 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1574 // Remove the session from storage directly.
1576 m_storage->deleteContext(key);
1577 m_log.info("removed session (%s)", key);
1579 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1580 Locker locker(xlog);
1581 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1583 throw ConfigurationException("SessionCache removal requires a StorageService.");
1587 // Remote the request.
1588 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1591 in.addmember("key").string(key);
1592 in.addmember("application_id").string(app.getId());
1594 DDF out = app.getServiceProvider().getListenerService()->send(in);
1599 void SSCache::dormant(const char* key)
1602 xmltooling::NDC ndc("dormant");
1605 m_log.debug("deleting local copy of session (%s)", key);
1607 // lock the cache for writing, which means we know nobody is sitting in find()
1610 // grab the entry from the table
1611 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1612 if (i==m_hashtable.end()) {
1617 // ok, remove the entry and lock it
1618 StoredSession* entry=i->second;
1619 m_hashtable.erase(key);
1625 // we can release the cache entry lock because we know we're not in the cache anymore
1631 void* SSCache::cleanup_fn(void* p)
1634 xmltooling::NDC ndc("cleanup");
1637 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1640 // First, let's block all signals
1641 Thread::mask_all_signals();
1644 auto_ptr<Mutex> mutex(Mutex::create());
1646 // Load our configuration details...
1647 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1648 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1649 int rerun_timer = 900;
1651 rerun_timer = XMLString::parseInt(tag);
1652 if (rerun_timer <= 0)
1658 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1660 while (!pcache->shutdown) {
1661 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1662 if (pcache->shutdown)
1665 // Ok, let's run through the cleanup process and clean out
1666 // really old sessions. This is a two-pass process. The
1667 // first pass is done holding a read-lock while we iterate over
1668 // the cache. The second pass doesn't need a lock because
1669 // the 'deletes' will lock the cache.
1671 // Pass 1: iterate over the map and find all entries that have not been
1672 // used in the allotted timeout.
1673 vector<string> stale_keys;
1674 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1676 pcache->m_log.debug("cleanup thread running");
1678 pcache->m_lock->rdlock();
1679 for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1680 // If the last access was BEFORE the stale timeout...
1682 time_t last=i->second->getLastAccess();
1683 i->second->unlock();
1685 stale_keys.push_back(i->first);
1687 pcache->m_lock->unlock();
1689 if (!stale_keys.empty()) {
1690 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1692 // Pass 2: walk through the list of stale entries and remove them from the cache
1693 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1694 pcache->dormant(j->c_str());
1697 pcache->m_log.debug("cleanup thread completed");
1700 pcache->m_log.info("cleanup thread exiting");
1708 void SSCache::receive(DDF& in, ostream& out)
1711 xmltooling::NDC ndc("receive");
1713 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1715 throw ListenerException("Application not found, check configuration?");
1717 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1718 const char* key=in["key"].string();
1720 throw ListenerException("Required parameters missing for session lookup.");
1722 // Do an unversioned read.
1725 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1727 DDFJanitor jan(ret);
1732 // Adjust for expiration to recover last access time and check timeout.
1733 unsigned long cacheTimeout = getCacheTimeout(*app);
1734 lastAccess -= cacheTimeout;
1735 time_t now=time(nullptr);
1737 // See if we need to check for a timeout.
1738 if (in["timeout"].string()) {
1740 auto_ptr_XMLCh dt(in["timeout"].string());
1741 DateTime dtobj(dt.get());
1742 dtobj.parseDateTime();
1743 timeout = dtobj.getEpoch();
1745 if (timeout > 0 && now - lastAccess >= timeout) {
1746 m_log.info("session timed out (ID: %s)", key);
1748 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1751 // Update storage expiration, if possible.
1753 m_storage->updateContext(key, now + cacheTimeout);
1755 catch (exception& ex) {
1756 m_log.error("failed to update session expiration: %s", ex.what());
1760 // Send the record back.
1763 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1764 const char* key=in["key"].string();
1766 throw ListenerException("Required parameters missing for session check.");
1768 // Do a versioned read.
1771 int curver = in["version"].integer();
1772 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1774 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1775 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1778 // Adjust for expiration to recover last access time and check timeout.
1779 unsigned long cacheTimeout = getCacheTimeout(*app);
1780 lastAccess -= cacheTimeout;
1781 time_t now=time(nullptr);
1783 // See if we need to check for a timeout.
1785 auto_ptr_XMLCh dt(in["timeout"].string());
1787 DateTime dtobj(dt.get());
1788 dtobj.parseDateTime();
1789 timeout = dtobj.getEpoch();
1792 if (timeout > 0 && now - lastAccess >= timeout) {
1793 m_log.info("session timed out (ID: %s)", key);
1794 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1797 // Update storage expiration, if possible.
1799 m_storage->updateContext(key, now + cacheTimeout);
1801 catch (exception& ex) {
1802 m_log.error("failed to update session expiration: %s", ex.what());
1806 // Send the record back.
1811 DDFJanitor jan(ret);
1815 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1816 const char* key=in["key"].string();
1818 throw ListenerException("Required parameter missing for session removal.");
1822 DDFJanitor jan(ret);