2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * StorageServiceSessionCache.cpp
20 * StorageService-based SessionCache implementation.
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
24 * layer their own cache plugin on top of this version either by delegating to it
25 * or using the remoting support. So this version will load sessions directly
26 * from the StorageService, instantiate enough to expose the Session API,
27 * and then delete everything when they're unlocked. All data in memory is always
28 * kept in sync with the StorageService (no lazy updates).
32 #include "Application.h"
33 #include "exceptions.h"
34 #include "ServiceProvider.h"
35 #include "SessionCacheEx.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "remoting/ListenerService.h"
39 #include "util/SPConstants.h"
42 #include <xmltooling/io/HTTPRequest.h>
43 #include <xmltooling/io/HTTPResponse.h>
44 #include <xmltooling/util/DateTime.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/ParserPool.h>
47 #include <xmltooling/util/Threads.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
52 # include <saml/exceptions.h>
53 # include <saml/SAMLConfig.h>
54 # include <saml/saml2/core/Assertions.h>
55 # include <saml/saml2/metadata/Metadata.h>
56 # include <xmltooling/XMLToolingConfig.h>
57 # include <xmltooling/util/StorageService.h>
58 using namespace opensaml::saml2md;
61 # include <xmltooling/util/DateTime.h>
64 using namespace shibsp;
65 using namespace opensaml;
66 using namespace xmltooling;
72 class SSCache : public SessionCacheEx
74 ,public virtual Remoted
78 SSCache(const DOMElement* e);
82 void receive(DDF& in, ostream& out);
85 const Application& app,
86 const HTTPRequest& httpRequest,
87 HTTPResponse& httpResponse,
89 const saml2md::EntityDescriptor* issuer=nullptr,
90 const XMLCh* protocol=nullptr,
91 const saml2::NameID* nameid=nullptr,
92 const XMLCh* authn_instant=nullptr,
93 const XMLCh* session_index=nullptr,
94 const XMLCh* authncontext_class=nullptr,
95 const XMLCh* authncontext_decl=nullptr,
96 const vector<const Assertion*>* tokens=nullptr,
97 const vector<Attribute*>* attributes=nullptr
99 vector<string>::size_type logout(
100 const Application& app,
101 const saml2md::EntityDescriptor* issuer,
102 const saml2::NameID& nameid,
103 const set<string>* indexes,
105 vector<string>& sessions
108 const Application& app,
109 const HTTPRequest& request,
110 const saml2md::EntityDescriptor* issuer,
111 const saml2::NameID& nameid,
112 const set<string>* indexes
115 Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
116 void remove(const Application& app, const char* key);
119 string active(const Application& app, const HTTPRequest& request) {
120 if (m_inboundHeader.empty()) {
121 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
122 const char* session_id = request.getCookie(shib_cookie.first.c_str());
123 return (session_id ? session_id : "");
126 string session_id = request.getHeader(m_inboundHeader.c_str());
127 if (!session_id.empty())
129 const char* p = request.getParameter(m_inboundHeader.c_str());
134 Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
135 string id = active(app, request);
137 return find(app, id.c_str(), client_addr, timeout);
141 Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
142 void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
144 unsigned long getCacheTimeout(const Application& app) {
145 // Computes offset for adjusting expiration of sessions.
146 // This can either be static, or dynamic based on the per-app session timeout.
148 return m_cacheTimeout;
149 pair<bool,unsigned int> timeout;
150 const PropertySet* props = app.getPropertySet("Sessions");
152 timeout = props->getUnsignedInt("timeout");
154 timeout.second = 3600;
156 return timeout.second + m_cacheAllowance;
162 StorageService* m_storage;
163 StorageService* m_storage_lite;
168 // maintain back-mappings of NameID/SessionIndex -> session key
169 void insert(const char* key, time_t expires, const char* name, const char* index);
170 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
172 bool m_cacheAssertions;
174 const DOMElement* m_root; // Only valid during initialization
175 unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
176 string m_inboundHeader,m_outboundHeader;
178 // inproc means we buffer sessions in memory
180 map<string,StoredSession*> m_hashtable;
182 // management of buffered sessions
183 void dormant(const char* key);
184 static void* cleanup_fn(void*);
187 CondWait* shutdown_wait;
188 Thread* cleanup_thread;
191 class StoredSession : public virtual Session
194 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
198 m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)), m_lock(nullptr) {
199 auto_ptr_XMLCh exp(m_obj["expires"].string());
201 DateTime iso(exp.get());
203 m_expires = iso.getEpoch();
207 const char* nameid = obj["nameid"].string();
209 // Parse and bind the document into an XMLObject.
210 istringstream instr(nameid);
211 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
212 XercesJanitor<DOMDocument> janitor(doc);
213 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
214 n->unmarshall(doc->getDocumentElement(), true);
216 m_nameid = n.release();
220 m_lock = Mutex::create();
226 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
229 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
245 const char* getID() const {
248 const char* getApplicationID() const {
249 return m_obj["application_id"].string();
251 const char* getClientAddress() const {
252 return m_obj["client_addr"].string();
254 const char* getEntityID() const {
255 return m_obj["entity_id"].string();
257 const char* getProtocol() const {
258 return m_obj["protocol"].string();
260 const char* getAuthnInstant() const {
261 return m_obj["authn_instant"].string();
264 const saml2::NameID* getNameID() const {
268 const char* getSessionIndex() const {
269 return m_obj["session_index"].string();
271 const char* getAuthnContextClassRef() const {
272 return m_obj["authncontext_class"].string();
274 const char* getAuthnContextDeclRef() const {
275 return m_obj["authncontext_decl"].string();
277 const vector<Attribute*>& getAttributes() const {
278 if (m_attributes.empty())
279 unmarshallAttributes();
282 const multimap<string,const Attribute*>& getIndexedAttributes() const {
283 if (m_attributeIndex.empty()) {
284 if (m_attributes.empty())
285 unmarshallAttributes();
286 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
287 const vector<string>& aliases = (*a)->getAliases();
288 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
289 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
292 return m_attributeIndex;
294 const vector<const char*>& getAssertionIDs() const {
296 DDF ids = m_obj["assertions"];
297 DDF id = ids.first();
298 while (id.isstring()) {
299 m_ids.push_back(id.string());
306 void validate(const Application& application, const char* client_addr, time_t* timeout);
309 void addAttributes(const vector<Attribute*>& attributes);
310 const Assertion* getAssertion(const char* id) const;
311 void addAssertion(Assertion* assertion);
314 time_t getExpiration() const { return m_expires; }
315 time_t getLastAccess() const { return m_lastAccess; }
318 void unmarshallAttributes() const;
322 saml2::NameID* m_nameid;
323 mutable map<string,Assertion*> m_tokens;
325 mutable vector<Attribute*> m_attributes;
326 mutable multimap<string,const Attribute*> m_attributeIndex;
327 mutable vector<const char*> m_ids;
330 time_t m_expires,m_lastAccess;
334 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
336 return new SSCache(e);
340 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
342 return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
345 void SHIBSP_API shibsp::registerSessionCaches()
347 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
358 void StoredSession::unmarshallAttributes() const
360 Attribute* attribute;
361 DDF attrs = m_obj["attributes"];
362 DDF attr = attrs.first();
363 while (!attr.isnull()) {
365 attribute = Attribute::unmarshall(attr);
366 m_attributes.push_back(attribute);
367 if (m_cache->m_log.isDebugEnabled())
368 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
369 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
371 catch (AttributeException& ex) {
372 const char* id = attr.first().name();
373 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
379 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
381 time_t now = time(nullptr);
385 if (now > m_expires) {
386 m_cache->m_log.info("session expired (ID: %s)", getID());
387 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
393 if (m_cache->m_log.isDebugEnabled())
394 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
395 if (!XMLString::equals(getClientAddress(),client_addr)) {
396 m_cache->m_log.warn("client address mismatch");
397 throw RetryableProfileException(
398 "Your IP address ($1) does not match the address recorded at the time the session was established.",
399 params(1,client_addr)
407 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
408 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
411 in.addmember("key").string(getID());
412 in.addmember("version").integer(m_obj["version"].integer());
414 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
415 #ifndef HAVE_GMTIME_R
416 struct tm* ptime=gmtime(timeout);
419 struct tm* ptime=gmtime_r(timeout,&res);
422 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
423 in.addmember("timeout").string(timebuf);
427 out=app.getServiceProvider().getListenerService()->send(in);
434 if (out.isstruct()) {
435 // We got an updated record back.
437 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
438 m_attributes.clear();
439 m_attributeIndex.clear();
446 if (!m_cache->m_storage)
447 throw ConfigurationException("Session touch requires a StorageService.");
449 // Do a versioned read.
452 int curver = m_obj["version"].integer();
453 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
455 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
456 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
459 // Adjust for expiration to recover last access time and check timeout.
460 unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
461 lastAccess -= cacheTimeout;
462 if (*timeout > 0 && now - lastAccess >= *timeout) {
463 m_cache->m_log.info("session timed out (ID: %s)", getID());
464 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
467 // Update storage expiration, if possible.
469 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
471 catch (exception& ex) {
472 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
476 // We got an updated record back.
478 istringstream in(record);
481 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
482 m_attributes.clear();
483 m_attributeIndex.clear();
488 throw ConfigurationException("Session touch requires a StorageService.");
497 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
500 xmltooling::NDC ndc("addAttributes");
503 if (!m_cache->m_storage)
504 throw ConfigurationException("Session modification requires a StorageService.");
506 m_cache->m_log.debug("adding attributes to session (%s)", getID());
511 DDF attrs = m_obj["attributes"];
513 attrs = m_obj.addmember("attributes").list();
514 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
515 attr = (*a)->marshall();
519 // Tentatively increment the version.
520 m_obj["version"].integer(m_obj["version"].integer()+1);
524 string record(str.str());
527 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
530 // Roll back modification to record.
531 m_obj["version"].integer(m_obj["version"].integer()-1);
532 vector<Attribute*>::size_type count = attributes.size();
534 attrs.last().destroy();
539 // Roll back modification to record.
540 m_obj["version"].integer(m_obj["version"].integer()-1);
541 vector<Attribute*>::size_type count = attributes.size();
543 attrs.last().destroy();
546 // Fatal problem with update.
547 throw IOException("Unable to update stored session.");
551 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
552 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
554 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
555 throw IOException("Unable to read back stored session.");
560 istringstream in(record);
564 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
565 m_attributes.clear();
566 m_attributeIndex.clear();
567 newobj["version"].integer(ver);
573 } while (ver < 0); // negative indicates a sync issue so we retry
575 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
577 xlog->log.infoStream() <<
578 "Added the following attributes to session (ID: " <<
580 ") for (applicationId: " <<
581 m_obj["application_id"].string() <<
583 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
584 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
587 // We own them now, so clean them up.
588 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
591 const Assertion* StoredSession::getAssertion(const char* id) const
593 if (!m_cache->m_storage)
594 throw ConfigurationException("Assertion retrieval requires a StorageService.");
596 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
597 if (i!=m_tokens.end())
601 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
602 throw FatalProfileException("Assertion not found in cache.");
604 // Parse and bind the document into an XMLObject.
605 istringstream instr(tokenstr);
606 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
607 XercesJanitor<DOMDocument> janitor(doc);
608 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
611 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
613 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
615 // Transfer ownership to us.
621 void StoredSession::addAssertion(Assertion* assertion)
624 xmltooling::NDC ndc("addAssertion");
627 if (!m_cache->m_storage)
628 throw ConfigurationException("Session modification requires a StorageService.");
631 throw FatalProfileException("Unknown object type passed to session for storage.");
633 auto_ptr_char id(assertion->getID());
635 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
638 if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
639 throw IOException("Unable to load expiration time for stored session.");
641 ostringstream tokenstr;
642 tokenstr << *assertion;
643 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
644 throw IOException("Attempted to insert duplicate assertion ID into session.");
648 DDF token = DDF(nullptr).string(id.get());
649 m_obj["assertions"].add(token);
651 // Tentatively increment the version.
652 m_obj["version"].integer(m_obj["version"].integer()+1);
656 string record(str.str());
659 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
663 m_obj["version"].integer(m_obj["version"].integer()-1);
664 m_cache->m_storage->deleteText(getID(), id.get());
670 m_obj["version"].integer(m_obj["version"].integer()-1);
673 // Fatal problem with update.
674 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
675 m_cache->m_storage->deleteText(getID(), id.get());
676 throw IOException("Unable to update stored session.");
680 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
681 ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
683 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
684 m_cache->m_storage->deleteText(getID(), id.get());
685 throw IOException("Unable to read back stored session.");
690 istringstream in(record);
694 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
695 m_attributes.clear();
696 m_attributeIndex.clear();
697 newobj["version"].integer(ver);
703 } while (ver < 0); // negative indicates a sync issue so we retry
708 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
711 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
712 id.get(), m_obj["application_id"].string(), getID()
718 SessionCache::SessionCache()
722 SessionCache::~SessionCache()
726 SessionCacheEx::SessionCacheEx()
730 SessionCacheEx::~SessionCacheEx()
734 SSCache::SSCache(const DOMElement* e)
735 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
737 m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true),
739 m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0),
740 m_lock(nullptr), shutdown(false), shutdown_wait(nullptr), cleanup_thread(nullptr)
742 SPConfig& conf = SPConfig::getConfig();
743 inproc = conf.isEnabled(SPConfig::InProcess);
745 static const XMLCh cacheAllowance[] = UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
746 static const XMLCh cacheAssertions[] = UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
747 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
748 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
749 static const XMLCh inboundHeader[] = UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
750 static const XMLCh outboundHeader[] = UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
751 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
752 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);
754 m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
755 m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
757 m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
758 m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
759 m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
762 if (conf.isEnabled(SPConfig::OutOfProcess)) {
763 string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
765 m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
767 m_log.info("bound to StorageService (%s)", ssid.c_str());
769 m_log.warn("specified StorageService (%s) not found", ssid.c_str());
772 m_storage = conf.getServiceProvider()->getStorageService(nullptr);
774 m_log.info("bound to arbitrary StorageService");
776 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
779 ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
781 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
783 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
785 m_log.warn("specified 'lite' StorageService (%s) not found", ssid.c_str());
787 if (!m_storage_lite) {
788 m_log.info("StorageService for 'lite' use not set, using standard StorageService");
789 m_storage_lite = m_storage;
792 m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
796 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
798 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
799 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
800 m_lock = RWLock::create();
801 shutdown_wait = CondWait::create();
802 cleanup_thread = Thread::create(&cleanup_fn, this);
806 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
807 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
808 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
809 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
812 m_log.info("no ListenerService available, cache remoting disabled");
821 // Shut down the cleanup thread and let it know...
823 shutdown_wait->signal();
824 cleanup_thread->join(nullptr);
826 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
829 delete cleanup_thread;
830 delete shutdown_wait;
834 SPConfig& conf = SPConfig::getConfig();
835 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
836 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
837 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
838 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
839 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
849 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
850 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
851 m_storage->deleteString("SessionCacheTest", temp.get());
854 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
857 if (strlen(name) > 255) {
858 dup = string(name).substr(0,255);
863 DDFJanitor jobj(obj);
865 // Since we can't guarantee uniqueness, check for an existing record.
868 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
870 // Existing record, so we need to unmarshall it.
871 istringstream in(record);
876 obj = DDF(nullptr).structure();
879 if (!index || !*index)
881 DDF sessions = obj.addmember(index);
882 if (!sessions.islist())
884 DDF session = DDF(nullptr).string(key);
885 sessions.add(session);
887 // Remarshall the record.
891 // Try and store it back...
893 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
895 // Out of sync, or went missing, so retry.
896 return insert(key, expires, name, index);
899 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
900 // Hit a dup, so just retry, hopefully hitting the other branch.
901 return insert(key, expires, name, index);
905 void SSCache::insert(
906 const Application& app,
907 const HTTPRequest& httpRequest,
908 HTTPResponse& httpResponse,
910 const saml2md::EntityDescriptor* issuer,
911 const XMLCh* protocol,
912 const saml2::NameID* nameid,
913 const XMLCh* authn_instant,
914 const XMLCh* session_index,
915 const XMLCh* authncontext_class,
916 const XMLCh* authncontext_decl,
917 const vector<const Assertion*>* tokens,
918 const vector<Attribute*>* attributes
922 xmltooling::NDC ndc("insert");
925 throw ConfigurationException("SessionCache insertion requires a StorageService.");
927 m_log.debug("creating new session");
929 time_t now = time(nullptr);
930 auto_ptr_char index(session_index);
931 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
932 auto_ptr_char name(nameid ? nameid->getName() : nullptr);
935 // Check for a pending logout.
937 strncpy(namebuf, name.get(), 255);
940 int ver = m_storage_lite->readText("Logout", namebuf, &pending);
943 DDFJanitor jpend(pendobj);
944 istringstream pstr(pending);
946 // IdP.SP.index contains logout expiration, if any.
947 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
948 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
949 if (!logexpstr && session_index) // we tried an exact session match, now try for nullptr
950 logexpstr = deadmenwalking["_shibnull"].string();
952 auto_ptr_XMLCh dt(logexpstr);
953 DateTime dtobj(dt.get());
954 dtobj.parseDateTime();
955 time_t logexp = dtobj.getEpoch();
956 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
957 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
962 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
964 // Store session properties in DDF.
965 DDF obj = DDF(key.get()).structure();
966 DDFJanitor entryobj(obj);
967 obj.addmember("version").integer(1);
968 obj.addmember("application_id").string(app.getId());
970 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
971 #ifndef HAVE_GMTIME_R
972 struct tm* ptime=gmtime(&expires);
975 struct tm* ptime=gmtime_r(&expires,&res);
978 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
979 obj.addmember("expires").string(timebuf);
981 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
983 obj.addmember("entity_id").string(entity_id.get());
985 auto_ptr_char prot(protocol);
986 obj.addmember("protocol").string(prot.get());
989 auto_ptr_char instant(authn_instant);
990 obj.addmember("authn_instant").string(instant.get());
993 obj.addmember("session_index").string(index.get());
994 if (authncontext_class) {
995 auto_ptr_char ac(authncontext_class);
996 obj.addmember("authncontext_class").string(ac.get());
998 if (authncontext_decl) {
999 auto_ptr_char ad(authncontext_decl);
1000 obj.addmember("authncontext_decl").string(ad.get());
1004 ostringstream namestr;
1006 obj.addmember("nameid").string(namestr.str().c_str());
1009 if (tokens && m_cacheAssertions) {
1010 obj.addmember("assertions").list();
1011 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1012 auto_ptr_char tokenid((*t)->getID());
1013 DDF tokid = DDF(nullptr).string(tokenid.get());
1014 obj["assertions"].add(tokid);
1020 DDF attrlist = obj.addmember("attributes").list();
1021 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1022 attr = (*a)->marshall();
1027 ostringstream record;
1030 m_log.debug("storing new session...");
1031 unsigned long cacheTimeout = getCacheTimeout(app);
1032 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1033 throw FatalProfileException("Attempted to create a session with a duplicate key.");
1035 // Store the reverse mapping for logout.
1038 insert(key.get(), expires, name.get(), index.get());
1040 catch (exception& ex) {
1041 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1044 if (tokens && m_cacheAssertions) {
1046 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1047 ostringstream tokenstr;
1049 auto_ptr_char tokenid((*t)->getID());
1050 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1051 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
1054 catch (exception& ex) {
1055 m_log.error("error storing assertion along with session: %s", ex.what());
1059 const char* pid = obj["entity_id"].string();
1060 const char* prot = obj["protocol"].string();
1061 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1062 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1064 // Transaction Logging
1065 string primaryAssertionID("none");
1066 if (m_cacheAssertions) {
1068 primaryAssertionID = obj["assertions"].first().string();
1071 auto_ptr_char tokenid(tokens->front()->getID());
1072 primaryAssertionID = tokenid.get();
1074 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1075 Locker locker(xlog);
1076 xlog->log.infoStream() <<
1077 "New session (ID: " <<
1079 ") with (applicationId: " <<
1081 ") for principal from (IdP: " <<
1082 (pid ? pid : "none") <<
1083 ") at (ClientAddress: " <<
1084 httpRequest.getRemoteAddr() <<
1085 ") with (NameIdentifier: " <<
1086 (nameid ? name.get() : "none") <<
1087 ") using (Protocol: " <<
1088 (prot ? prot : "none") <<
1089 ") from (AssertionID: " <<
1090 primaryAssertionID <<
1094 xlog->log.infoStream() <<
1095 "Cached the following attributes with session (ID: " <<
1097 ") for (applicationId: " <<
1100 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
1101 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
1102 xlog->log.info("}");
1105 if (m_outboundHeader.empty()) {
1106 time_t cookieLifetime = 0;
1107 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1108 string k(key.get());
1109 k += shib_cookie.second;
1111 if (cookieLifetime > 0) {
1112 cookieLifetime += now;
1113 #ifndef HAVE_GMTIME_R
1114 ptime=gmtime(&cookieLifetime);
1116 ptime=gmtime_r(&cookieLifetime,&res);
1118 char cookietimebuf[64];
1119 strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1123 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1126 // Use an arbitrary header to pass back the session ID instead of a cookie.
1127 httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1131 bool SSCache::matches(
1132 const Application& app,
1133 const xmltooling::HTTPRequest& request,
1134 const saml2md::EntityDescriptor* issuer,
1135 const saml2::NameID& nameid,
1136 const set<string>* indexes
1139 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1141 Session* session = find(app, request);
1143 Locker locker(session, false);
1144 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1145 stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1146 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1150 catch (exception& ex) {
1151 m_log.error("error while matching session: %s", ex.what());
1156 vector<string>::size_type SSCache::logout(
1157 const Application& app,
1158 const saml2md::EntityDescriptor* issuer,
1159 const saml2::NameID& nameid,
1160 const set<string>* indexes,
1162 vector<string>& sessionsKilled
1166 xmltooling::NDC ndc("logout");
1170 throw ConfigurationException("SessionCache insertion requires a StorageService.");
1172 auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1173 auto_ptr_char name(nameid.getName());
1175 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1177 if (strlen(name.get()) > 255)
1178 const_cast<char*>(name.get())[255] = 0;
1181 DDFJanitor jobj(obj);
1186 // Record the logout to prevent post-delivered assertions.
1187 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1188 #ifndef HAVE_GMTIME_R
1189 struct tm* ptime=gmtime(&expires);
1192 struct tm* ptime=gmtime_r(&expires,&res);
1195 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1198 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1200 istringstream lin(record);
1204 obj = DDF(nullptr).structure();
1207 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1208 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1210 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1211 root.addmember(x->c_str()).string(timebuf);
1214 root.addmember("_shibnull").string(timebuf);
1222 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1224 // Out of sync, or went missing, so retry.
1225 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1228 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1229 // Hit a dup, so just retry, hopefully hitting the other branch.
1230 return logout(app, issuer, nameid, indexes, expires, sessionsKilled);
1237 // Read in potentially matching sessions.
1238 ver = m_storage_lite->readText("NameID", name.get(), &record);
1240 m_log.debug("no active sessions to logout for supplied issuer and subject");
1244 istringstream in(record);
1247 // The record contains child lists for each known session index.
1249 DDF sessions = obj.first();
1250 while (sessions.islist()) {
1251 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1252 key = sessions.first();
1253 while (key.isstring()) {
1254 // Fetch the session for comparison.
1255 Session* session = nullptr;
1257 session = find(app, key.string());
1259 catch (exception& ex) {
1260 m_log.error("error locating session (%s): %s", key.string(), ex.what());
1264 Locker locker(session, false);
1266 if (XMLString::equals(session->getEntityID(), entityID.get())) {
1268 if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1269 sessionsKilled.push_back(key.string());
1273 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1277 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1281 // Session's gone, so...
1282 sessionsKilled.push_back(key.string());
1285 key = sessions.next();
1288 // No sessions left for this index?
1289 if (sessions.first().isnull())
1292 sessions = obj.next();
1295 if (obj.first().isnull())
1298 // If possible, write back the mapping record (this isn't crucial).
1301 m_storage_lite->deleteText("NameID", name.get());
1303 else if (!sessionsKilled.empty()) {
1306 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1307 m_log.warn("logout mapping record changed behind us, leaving it alone");
1310 catch (exception& ex) {
1311 m_log.error("error updating logout mapping record: %s", ex.what());
1314 return sessionsKilled.size();
1317 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1319 if (!XMLString::equals(n1.getName(), n2.getName()))
1322 const XMLCh* s1 = n1.getFormat();
1323 const XMLCh* s2 = n2.getFormat();
1325 s1 = saml2::NameID::UNSPECIFIED;
1327 s2 = saml2::NameID::UNSPECIFIED;
1328 if (!XMLString::equals(s1,s2))
1331 s1 = n1.getNameQualifier();
1332 s2 = n2.getNameQualifier();
1337 if (!XMLString::equals(s1,s2))
1340 s1 = n1.getSPNameQualifier();
1341 s2 = n2.getSPNameQualifier();
1346 if (!XMLString::equals(s1,s2))
1354 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1357 xmltooling::NDC ndc("find");
1359 StoredSession* session=nullptr;
1362 m_log.debug("searching local cache for session (%s)", key);
1364 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1365 if (i!=m_hashtable.end()) {
1366 // Save off and lock the session.
1367 session = i->second;
1370 m_log.debug("session found locally, validating it for use");
1378 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1379 m_log.debug("session not found locally, remoting the search");
1380 // Remote the request.
1381 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1384 in.addmember("key").string(key);
1385 in.addmember("application_id").string(app.getId());
1386 if (timeout && *timeout) {
1387 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1388 #ifndef HAVE_GMTIME_R
1389 struct tm* ptime=gmtime(timeout);
1392 struct tm* ptime=gmtime_r(timeout,&res);
1395 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1396 in.addmember("timeout").string(timebuf);
1400 out=app.getServiceProvider().getListenerService()->send(in);
1401 if (!out.isstruct()) {
1403 m_log.debug("session not found in remote cache");
1407 // Wrap the results in a local entry and save it.
1408 session = new StoredSession(this, out);
1409 // The remote end has handled timeout issues, we handle address and expiration checks.
1418 // We're out of process, so we can search the storage service directly.
1421 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1423 m_log.debug("searching for session (%s)", key);
1428 int ver = m_storage->readText(key, "session", &record, &lastAccess);
1432 m_log.debug("reconstituting session and checking validity");
1434 istringstream in(record);
1437 unsigned long cacheTimeout = getCacheTimeout(app);
1438 lastAccess -= cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
1439 time_t now=time(nullptr);
1441 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1442 m_log.info("session timed out (ID: %s)", key);
1444 const char* eid = obj["entity_id"].string();
1447 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1451 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1455 // Update storage expiration, if possible.
1457 m_storage->updateContext(key, now + cacheTimeout);
1459 catch (exception& ex) {
1460 m_log.error("failed to update session expiration: %s", ex.what());
1464 // Wrap the results in a local entry and save it.
1465 session = new StoredSession(this, obj);
1466 // We handled timeout issues, still need to handle address and expiration checks.
1469 throw ConfigurationException("SessionCache search requires a StorageService.");
1474 // Lock for writing and repeat the search to avoid duplication.
1476 SharedLock shared(m_lock, false);
1477 if (m_hashtable.count(key)) {
1478 // We're using an existing session entry.
1480 session = m_hashtable[key];
1484 m_hashtable[key]=session;
1490 if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1491 m_log.error("an application (%s) tried to access another application's session", app.getId());
1496 // Verify currency and update the timestamp if indicated by caller.
1498 session->validate(app, client_addr, timeout);
1509 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1511 string id = active(app, request);
1515 Session* session = find(app, id.c_str(), client_addr, timeout);
1518 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1520 if (m_outboundHeader.empty()) {
1521 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1522 string exp(shib_cookie.second);
1523 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1524 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1527 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1531 catch (exception&) {
1532 if (m_outboundHeader.empty()) {
1533 HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1535 if (m_outboundHeader.empty()) {
1536 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1537 string exp(shib_cookie.second);
1538 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1539 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1542 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1551 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1553 if (m_inboundHeader.empty()) {
1554 pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1555 const char* session_id = request.getCookie(shib_cookie.first.c_str());
1556 if (session_id && *session_id) {
1558 if (m_outboundHeader.empty()) {
1559 string exp(shib_cookie.second);
1560 exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1561 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1564 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1567 remove(app, session_id);
1571 string session_id = request.getHeader(m_inboundHeader.c_str());
1572 if (session_id.empty()) {
1573 const char* p = request.getParameter(m_inboundHeader.c_str());
1577 if (!session_id.empty()) {
1578 if (response && !m_outboundHeader.empty())
1579 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1580 remove(app, session_id.c_str());
1585 void SSCache::remove(const Application& app, const char* key)
1588 xmltooling::NDC ndc("remove");
1590 // Take care of local copy.
1594 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1595 // Remove the session from storage directly.
1597 m_storage->deleteContext(key);
1598 m_log.info("removed session (%s)", key);
1600 TransactionLog* xlog = app.getServiceProvider().getTransactionLog();
1601 Locker locker(xlog);
1602 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", app.getId(), key);
1604 throw ConfigurationException("SessionCache removal requires a StorageService.");
1608 // Remote the request.
1609 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1612 in.addmember("key").string(key);
1613 in.addmember("application_id").string(app.getId());
1615 DDF out = app.getServiceProvider().getListenerService()->send(in);
1620 void SSCache::dormant(const char* key)
1623 xmltooling::NDC ndc("dormant");
1626 m_log.debug("deleting local copy of session (%s)", key);
1628 // lock the cache for writing, which means we know nobody is sitting in find()
1631 // grab the entry from the table
1632 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1633 if (i==m_hashtable.end()) {
1638 // ok, remove the entry and lock it
1639 StoredSession* entry=i->second;
1640 m_hashtable.erase(key);
1646 // we can release the cache entry lock because we know we're not in the cache anymore
1652 void* SSCache::cleanup_fn(void* p)
1655 xmltooling::NDC ndc("cleanup");
1658 SSCache* pcache = reinterpret_cast<SSCache*>(p);
1661 // First, let's block all signals
1662 Thread::mask_all_signals();
1665 auto_ptr<Mutex> mutex(Mutex::create());
1667 // Load our configuration details...
1668 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1669 const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1670 int rerun_timer = 900;
1672 rerun_timer = XMLString::parseInt(tag);
1673 if (rerun_timer <= 0)
1679 pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1681 while (!pcache->shutdown) {
1682 pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1683 if (pcache->shutdown)
1686 // Ok, let's run through the cleanup process and clean out
1687 // really old sessions. This is a two-pass process. The
1688 // first pass is done holding a read-lock while we iterate over
1689 // the cache. The second pass doesn't need a lock because
1690 // the 'deletes' will lock the cache.
1692 // Pass 1: iterate over the map and find all entries that have not been
1693 // used in the allotted timeout.
1694 vector<string> stale_keys;
1695 time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1697 pcache->m_log.debug("cleanup thread running");
1699 pcache->m_lock->rdlock();
1700 for (map<string,StoredSession*>::const_iterator i=pcache->m_hashtable.begin(); i!=pcache->m_hashtable.end(); ++i) {
1701 // If the last access was BEFORE the stale timeout...
1703 time_t last=i->second->getLastAccess();
1704 i->second->unlock();
1706 stale_keys.push_back(i->first);
1708 pcache->m_lock->unlock();
1710 if (!stale_keys.empty()) {
1711 pcache->m_log.info("purging %d old sessions", stale_keys.size());
1713 // Pass 2: walk through the list of stale entries and remove them from the cache
1714 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
1715 pcache->dormant(j->c_str());
1718 pcache->m_log.debug("cleanup thread completed");
1721 pcache->m_log.info("cleanup thread exiting");
1729 void SSCache::receive(DDF& in, ostream& out)
1732 xmltooling::NDC ndc("receive");
1734 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1736 throw ListenerException("Application not found, check configuration?");
1738 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1739 const char* key=in["key"].string();
1741 throw ListenerException("Required parameters missing for session lookup.");
1743 // Do an unversioned read.
1746 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1748 DDFJanitor jan(ret);
1753 // Adjust for expiration to recover last access time and check timeout.
1754 unsigned long cacheTimeout = getCacheTimeout(*app);
1755 lastAccess -= cacheTimeout;
1756 time_t now=time(nullptr);
1758 // See if we need to check for a timeout.
1759 if (in["timeout"].string()) {
1761 auto_ptr_XMLCh dt(in["timeout"].string());
1762 DateTime dtobj(dt.get());
1763 dtobj.parseDateTime();
1764 timeout = dtobj.getEpoch();
1766 if (timeout > 0 && now - lastAccess >= timeout) {
1767 m_log.info("session timed out (ID: %s)", key);
1769 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1772 // Update storage expiration, if possible.
1774 m_storage->updateContext(key, now + cacheTimeout);
1776 catch (exception& ex) {
1777 m_log.error("failed to update session expiration: %s", ex.what());
1781 // Send the record back.
1784 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1785 const char* key=in["key"].string();
1787 throw ListenerException("Required parameters missing for session check.");
1789 // Do a versioned read.
1792 int curver = in["version"].integer();
1793 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1795 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1796 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1799 // Adjust for expiration to recover last access time and check timeout.
1800 unsigned long cacheTimeout = getCacheTimeout(*app);
1801 lastAccess -= cacheTimeout;
1802 time_t now=time(nullptr);
1804 // See if we need to check for a timeout.
1806 auto_ptr_XMLCh dt(in["timeout"].string());
1808 DateTime dtobj(dt.get());
1809 dtobj.parseDateTime();
1810 timeout = dtobj.getEpoch();
1813 if (timeout > 0 && now - lastAccess >= timeout) {
1814 m_log.info("session timed out (ID: %s)", key);
1815 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1818 // Update storage expiration, if possible.
1820 m_storage->updateContext(key, now + cacheTimeout);
1822 catch (exception& ex) {
1823 m_log.error("failed to update session expiration: %s", ex.what());
1827 // Send the record back.
1832 DDFJanitor jan(ret);
1836 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1837 const char* key=in["key"].string();
1839 throw ListenerException("Required parameter missing for session removal.");
1843 DDFJanitor jan(ret);