2 * Copyright 2001-2007 Internet2
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
18 * StorageServiceSessionCache.cpp
\r
20 * StorageService-based SessionCache implementation.
\r
22 * Instead of optimizing this plugin with a buffering scheme that keeps objects around
\r
23 * and avoids extra parsing steps, I'm assuming that systems that require such can
\r
24 * layer their own cache plugin on top of this version either by delegating to it
\r
25 * or using the remoting support. So this version will load sessions directly
\r
26 * from the StorageService, instantiate enough to expose the Session API,
\r
27 * and then delete everything when they're unlocked. All data in memory is always
\r
28 * kept in sync with the StorageService (no lazy updates).
\r
31 #include "internal.h"
\r
32 #include "Application.h"
\r
33 #include "exceptions.h"
\r
34 #include "ServiceProvider.h"
\r
35 #include "SessionCacheEx.h"
\r
36 #include "TransactionLog.h"
\r
37 #include "attribute/Attribute.h"
\r
38 #include "remoting/ListenerService.h"
\r
39 #include "util/SPConstants.h"
\r
41 #include <xmltooling/util/NDC.h>
\r
42 #include <xmltooling/util/XMLHelper.h>
\r
43 #include <xercesc/util/XMLUniDefs.hpp>
\r
46 # include <saml/SAMLConfig.h>
\r
47 # include <xmltooling/util/StorageService.h>
\r
48 using namespace opensaml::saml2md;
\r
51 # include <xmltooling/util/DateTime.h>
\r
54 using namespace shibsp;
\r
55 using namespace opensaml;
\r
56 using namespace xmltooling;
\r
57 using namespace std;
\r
61 class StoredSession;
\r
62 class SSCache : public SessionCacheEx
\r
64 ,public virtual Remoted
\r
68 SSCache(const DOMElement* e);
\r
72 void receive(DDF& in, ostream& out);
\r
75 const Application& application,
\r
76 const HTTPRequest& httpRequest,
\r
77 HTTPResponse& httpResponse,
\r
79 const saml2md::EntityDescriptor* issuer=NULL,
\r
80 const XMLCh* protocol=NULL,
\r
81 const saml2::NameID* nameid=NULL,
\r
82 const XMLCh* authn_instant=NULL,
\r
83 const XMLCh* session_index=NULL,
\r
84 const XMLCh* authncontext_class=NULL,
\r
85 const XMLCh* authncontext_decl=NULL,
\r
86 const vector<const Assertion*>* tokens=NULL,
\r
87 const vector<Attribute*>* attributes=NULL
\r
89 vector<string>::size_type logout(
\r
90 const Application& application,
\r
91 const saml2md::EntityDescriptor* issuer,
\r
92 const saml2::NameID& nameid,
\r
93 const set<string>* indexes,
\r
95 vector<string>& sessions
\r
98 const Application& application,
\r
99 const xmltooling::HTTPRequest& request,
\r
100 const saml2md::EntityDescriptor* issuer,
\r
101 const saml2::NameID& nameid,
\r
102 const set<string>* indexes
\r
105 Session* find(const Application& application, const char* key, const char* client_addr=NULL, time_t* timeout=NULL);
\r
106 void remove(const Application& application, const char* key);
\r
109 string active(const Application& application, const xmltooling::HTTPRequest& request) {
\r
110 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
\r
111 const char* session_id = request.getCookie(shib_cookie.first.c_str());
\r
112 return (session_id ? session_id : "");
\r
115 Session* find(const Application& application, const HTTPRequest& request, const char* client_addr=NULL, time_t* timeout=NULL) {
\r
116 string id = active(application, request);
\r
118 return find(application, id.c_str(), client_addr, timeout);
\r
122 void remove(const Application& application, const HTTPRequest& request, HTTPResponse* response=NULL) {
\r
123 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
\r
124 const char* session_id = request.getCookie(shib_cookie.first.c_str());
\r
125 if (session_id && *session_id) {
\r
127 string exp(shib_cookie.second);
128 exp += "; expires=Mon, 01-Jan-2001 00:00:00 GMT";
\r
129 response->setCookie(shib_cookie.first.c_str(), exp.c_str());
\r
131 remove(application, session_id);
\r
139 unsigned long m_cacheTimeout;
\r
140 #ifndef SHIBSP_LITE
\r
141 StorageService* m_storage;
\r
142 StorageService* m_storage_lite;
\r
146 #ifndef SHIBSP_LITE
\r
147 // maintain back-mappings of NameID/SessionIndex -> session key
\r
148 void insert(const char* key, time_t expires, const char* name, const char* index);
\r
149 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
\r
152 const DOMElement* m_root; // Only valid during initialization
\r
153 unsigned long m_inprocTimeout;
\r
155 // inproc means we buffer sessions in memory
\r
157 map<string,StoredSession*> m_hashtable;
\r
159 // management of buffered sessions
\r
160 void dormant(const char* key);
\r
161 static void* cleanup_fn(void*);
\r
163 CondWait* shutdown_wait;
\r
164 Thread* cleanup_thread;
\r
167 class StoredSession : public virtual Session
\r
170 StoredSession(SSCache* cache, DDF& obj) : m_obj(obj),
\r
171 #ifndef SHIBSP_LITE
\r
174 m_cache(cache), m_expires(0), m_lastAccess(time(NULL)), m_lock(NULL) {
\r
175 auto_ptr_XMLCh exp(m_obj["expires"].string());
\r
177 DateTime iso(exp.get());
\r
178 iso.parseDateTime();
\r
179 m_expires = iso.getEpoch();
\r
182 #ifndef SHIBSP_LITE
\r
183 const char* nameid = obj["nameid"].string();
\r
185 // Parse and bind the document into an XMLObject.
\r
186 istringstream instr(nameid);
\r
187 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
188 XercesJanitor<DOMDocument> janitor(doc);
\r
189 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
\r
190 n->unmarshall(doc->getDocumentElement(), true);
\r
192 m_nameid = n.release();
\r
196 m_lock = Mutex::create();
\r
202 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
203 #ifndef SHIBSP_LITE
\r
205 for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
\r
221 const char* getID() const {
\r
222 return m_obj.name();
\r
224 const char* getApplicationID() const {
\r
225 return m_obj["application_id"].string();
\r
227 const char* getClientAddress() const {
\r
228 return m_obj["client_addr"].string();
\r
230 const char* getEntityID() const {
\r
231 return m_obj["entity_id"].string();
\r
233 const char* getProtocol() const {
\r
234 return m_obj["protocol"].string();
\r
236 const char* getAuthnInstant() const {
\r
237 return m_obj["authn_instant"].string();
\r
239 #ifndef SHIBSP_LITE
\r
240 const saml2::NameID* getNameID() const {
\r
244 const char* getSessionIndex() const {
\r
245 return m_obj["session_index"].string();
\r
247 const char* getAuthnContextClassRef() const {
\r
248 return m_obj["authncontext_class"].string();
\r
250 const char* getAuthnContextDeclRef() const {
\r
251 return m_obj["authncontext_decl"].string();
\r
253 const vector<Attribute*>& getAttributes() const {
\r
254 if (m_attributes.empty())
\r
255 unmarshallAttributes();
\r
256 return m_attributes;
\r
258 const multimap<string,const Attribute*>& getIndexedAttributes() const {
\r
259 if (m_attributeIndex.empty()) {
\r
260 if (m_attributes.empty())
\r
261 unmarshallAttributes();
\r
262 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
\r
263 const vector<string>& aliases = (*a)->getAliases();
\r
264 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
\r
265 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
\r
268 return m_attributeIndex;
\r
270 const vector<const char*>& getAssertionIDs() const {
\r
271 if (m_ids.empty()) {
\r
272 DDF ids = m_obj["assertions"];
\r
273 DDF id = ids.first();
\r
274 while (id.isstring()) {
\r
275 m_ids.push_back(id.string());
\r
282 void validate(const Application& application, const char* client_addr, time_t* timeout);
\r
284 #ifndef SHIBSP_LITE
\r
285 void addAttributes(const vector<Attribute*>& attributes);
\r
286 const Assertion* getAssertion(const char* id) const;
\r
287 void addAssertion(Assertion* assertion);
\r
290 time_t getExpiration() const { return m_expires; }
\r
291 time_t getLastAccess() const { return m_lastAccess; }
\r
294 void unmarshallAttributes() const;
\r
297 #ifndef SHIBSP_LITE
\r
298 saml2::NameID* m_nameid;
\r
299 mutable map<string,Assertion*> m_tokens;
\r
301 mutable vector<Attribute*> m_attributes;
\r
302 mutable multimap<string,const Attribute*> m_attributeIndex;
\r
303 mutable vector<const char*> m_ids;
\r
306 time_t m_expires,m_lastAccess;
\r
310 SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
\r
312 return new SSCache(e);
\r
316 void SHIBSP_API shibsp::registerSessionCaches()
\r
318 SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
\r
321 void StoredSession::unmarshallAttributes() const
\r
323 Attribute* attribute;
\r
324 DDF attrs = m_obj["attributes"];
\r
325 DDF attr = attrs.first();
\r
326 while (!attr.isnull()) {
\r
328 attribute = Attribute::unmarshall(attr);
\r
329 m_attributes.push_back(attribute);
\r
330 if (m_cache->m_log.isDebugEnabled())
\r
331 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
\r
332 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
\r
334 catch (AttributeException& ex) {
\r
335 const char* id = attr.first().name();
\r
336 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
\r
338 attr = attrs.next();
\r
342 void StoredSession::validate(const Application& application, const char* client_addr, time_t* timeout)
\r
344 time_t now = time(NULL);
\r
346 // Basic expiration?
\r
347 if (m_expires > 0) {
\r
348 if (now > m_expires) {
\r
349 m_cache->m_log.info("session expired (ID: %s)", getID());
\r
350 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
356 if (m_cache->m_log.isDebugEnabled())
\r
357 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
\r
358 if (!XMLString::equals(getClientAddress(),client_addr)) {
\r
359 m_cache->m_log.warn("client address mismatch");
\r
360 throw RetryableProfileException(
\r
361 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
362 params(1,client_addr)
\r
370 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
\r
371 DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
\r
372 DDFJanitor jin(in);
\r
374 in.addmember("key").string(getID());
\r
375 in.addmember("version").integer(m_obj["version"].integer());
\r
377 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
378 #ifndef HAVE_GMTIME_R
\r
379 struct tm* ptime=gmtime(timeout);
\r
382 struct tm* ptime=gmtime_r(timeout,&res);
\r
385 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
386 in.addmember("timeout").string(timebuf);
\r
390 out=application.getServiceProvider().getListenerService()->send(in);
\r
397 if (out.isstruct()) {
\r
398 // We got an updated record back.
\r
400 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
401 m_attributes.clear();
\r
402 m_attributeIndex.clear();
\r
408 #ifndef SHIBSP_LITE
\r
409 if (!m_cache->m_storage)
\r
410 throw ConfigurationException("Session touch requires a StorageService.");
\r
412 // Do a versioned read.
\r
415 int curver = m_obj["version"].integer();
\r
416 int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
\r
418 m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
\r
419 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
422 // Adjust for expiration to recover last access time and check timeout.
\r
423 lastAccess -= m_cache->m_cacheTimeout;
\r
424 if (*timeout > 0 && now - lastAccess >= *timeout) {
\r
425 m_cache->m_log.info("session timed out (ID: %s)", getID());
\r
426 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
429 // Update storage expiration, if possible.
\r
431 m_cache->m_storage->updateContext(getID(), now + m_cache->m_cacheTimeout);
\r
433 catch (exception& ex) {
\r
434 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
\r
437 if (ver > curver) {
\r
438 // We got an updated record back.
\r
440 istringstream in(record);
\r
443 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
444 m_attributes.clear();
\r
445 m_attributeIndex.clear();
\r
450 throw ConfigurationException("Session touch requires a StorageService.");
\r
454 m_lastAccess = now;
\r
457 #ifndef SHIBSP_LITE
\r
459 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
\r
462 xmltooling::NDC ndc("addAttributes");
\r
465 if (!m_cache->m_storage)
\r
466 throw ConfigurationException("Session modification requires a StorageService.");
\r
468 m_cache->m_log.debug("adding attributes to session (%s)", getID());
\r
473 DDF attrs = m_obj["attributes"];
\r
474 if (!attrs.islist())
\r
475 attrs = m_obj.addmember("attributes").list();
\r
476 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
\r
477 attr = (*a)->marshall();
\r
481 // Tentatively increment the version.
\r
482 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
486 string record(str.str());
\r
489 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
491 catch (exception&) {
\r
492 // Roll back modification to record.
\r
493 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
494 vector<Attribute*>::size_type count = attributes.size();
\r
496 attrs.last().destroy();
\r
501 // Roll back modification to record.
\r
502 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
503 vector<Attribute*>::size_type count = attributes.size();
\r
505 attrs.last().destroy();
\r
508 // Fatal problem with update.
\r
509 throw IOException("Unable to update stored session.");
\r
511 else if (ver < 0) {
\r
513 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
514 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
516 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
517 throw IOException("Unable to read back stored session.");
\r
522 istringstream in(record);
\r
526 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
527 m_attributes.clear();
\r
528 m_attributeIndex.clear();
\r
529 newobj["version"].integer(ver);
\r
535 } while (ver < 0); // negative indicates a sync issue so we retry
\r
537 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
538 Locker locker(xlog);
\r
539 xlog->log.infoStream() <<
\r
540 "Added the following attributes to session (ID: " <<
\r
542 ") for (applicationId: " <<
\r
543 m_obj["application_id"].string() <<
\r
545 for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
\r
546 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
547 xlog->log.info("}");
\r
549 // We own them now, so clean them up.
\r
550 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
\r
553 const Assertion* StoredSession::getAssertion(const char* id) const
\r
555 if (!m_cache->m_storage)
\r
556 throw ConfigurationException("Assertion retrieval requires a StorageService.");
\r
558 map<string,Assertion*>::const_iterator i = m_tokens.find(id);
\r
559 if (i!=m_tokens.end())
\r
563 if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
\r
564 throw FatalProfileException("Assertion not found in cache.");
\r
566 // Parse and bind the document into an XMLObject.
\r
567 istringstream instr(tokenstr);
\r
568 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
\r
569 XercesJanitor<DOMDocument> janitor(doc);
\r
570 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
\r
573 Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
\r
575 throw FatalProfileException("Request for cached assertion returned an unknown object type.");
\r
577 // Transfer ownership to us.
\r
578 xmlObject.release();
\r
579 m_tokens[id]=token;
\r
583 void StoredSession::addAssertion(Assertion* assertion)
\r
586 xmltooling::NDC ndc("addAssertion");
\r
589 if (!m_cache->m_storage)
\r
590 throw ConfigurationException("Session modification requires a StorageService.");
\r
593 throw FatalProfileException("Unknown object type passed to session for storage.");
\r
595 auto_ptr_char id(assertion->getID());
\r
597 m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
\r
600 if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
\r
601 throw IOException("Unable to load expiration time for stored session.");
\r
603 ostringstream tokenstr;
\r
604 tokenstr << *assertion;
\r
605 if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
\r
606 throw IOException("Attempted to insert duplicate assertion ID into session.");
\r
610 DDF token = DDF(NULL).string(id.get());
\r
611 m_obj["assertions"].add(token);
\r
613 // Tentatively increment the version.
\r
614 m_obj["version"].integer(m_obj["version"].integer()+1);
\r
618 string record(str.str());
\r
621 ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
\r
623 catch (exception&) {
\r
625 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
626 m_cache->m_storage->deleteText(getID(), id.get());
\r
632 m_obj["version"].integer(m_obj["version"].integer()-1);
\r
635 // Fatal problem with update.
\r
636 m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
\r
637 m_cache->m_storage->deleteText(getID(), id.get());
\r
638 throw IOException("Unable to update stored session.");
\r
640 else if (ver < 0) {
\r
642 m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
\r
643 ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
\r
645 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
\r
646 m_cache->m_storage->deleteText(getID(), id.get());
\r
647 throw IOException("Unable to read back stored session.");
\r
652 istringstream in(record);
\r
656 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
\r
657 m_attributes.clear();
\r
658 m_attributeIndex.clear();
\r
659 newobj["version"].integer(ver);
\r
665 } while (ver < 0); // negative indicates a sync issue so we retry
\r
670 TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
\r
671 Locker locker(xlog);
\r
673 "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
\r
674 id.get(), m_obj["application_id"].string(), getID()
\r
680 SSCache::SSCache(const DOMElement* e)
\r
681 : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true), m_cacheTimeout(3600),
\r
682 #ifndef SHIBSP_LITE
\r
683 m_storage(NULL), m_storage_lite(NULL),
\r
685 m_root(e), m_inprocTimeout(900), m_lock(NULL), shutdown(false), shutdown_wait(NULL), cleanup_thread(NULL)
\r
687 static const XMLCh cacheTimeout[] = UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
\r
688 static const XMLCh inprocTimeout[] = UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
\r
689 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
\r
690 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);
\r
692 SPConfig& conf = SPConfig::getConfig();
\r
693 inproc = conf.isEnabled(SPConfig::InProcess);
\r
696 const XMLCh* tag=e->getAttributeNS(NULL,cacheTimeout);
\r
698 m_cacheTimeout = XMLString::parseInt(tag);
\r
699 if (!m_cacheTimeout)
\r
700 m_cacheTimeout=3600;
\r
703 const XMLCh* tag=e->getAttributeNS(NULL,inprocTimeout);
\r
705 m_inprocTimeout = XMLString::parseInt(tag);
\r
706 if (!m_inprocTimeout)
\r
707 m_inprocTimeout=900;
\r
712 #ifndef SHIBSP_LITE
\r
713 if (conf.isEnabled(SPConfig::OutOfProcess)) {
\r
714 const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
\r
716 auto_ptr_char ssid(tag);
\r
717 m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
\r
719 m_log.info("bound to StorageService (%s)", ssid.get());
\r
722 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
\r
724 tag = e ? e->getAttributeNS(NULL,_StorageServiceLite) : NULL;
\r
726 auto_ptr_char ssid(tag);
\r
727 m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.get());
\r
728 if (m_storage_lite)
\r
729 m_log.info("bound to StorageServiceLite (%s)", ssid.get());
\r
731 if (!m_storage_lite) {
\r
732 m_log.info("No StorageServiceLite specified. Using standard StorageService.");
\r
733 m_storage_lite = m_storage;
\r
738 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
740 if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
\r
741 throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
\r
742 m_lock = RWLock::create();
\r
743 shutdown_wait = CondWait::create();
\r
744 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
\r
746 #ifndef SHIBSP_LITE
\r
748 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
749 listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
750 listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
751 listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
754 m_log.info("no ListenerService available, cache remoting disabled");
\r
760 SSCache::~SSCache()
\r
763 // Shut down the cleanup thread and let it know...
\r
765 shutdown_wait->signal();
\r
766 cleanup_thread->join(NULL);
\r
768 for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
\r
770 delete shutdown_wait;
\r
772 #ifndef SHIBSP_LITE
\r
774 SPConfig& conf = SPConfig::getConfig();
\r
775 ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
\r
776 if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
\r
777 listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
778 listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
779 listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
\r
785 #ifndef SHIBSP_LITE
\r
787 void SSCache::test()
\r
789 auto_ptr_char temp(SAMLConfig::getConfig().generateIdentifier());
\r
790 m_storage->createString("SessionCacheTest", temp.get(), "Test", time(NULL) + 60);
\r
791 m_storage->deleteString("SessionCacheTest", temp.get());
\r
794 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
\r
797 if (strlen(name) > 255) {
\r
798 dup = string(name).substr(0,255);
\r
799 name = dup.c_str();
\r
803 DDFJanitor jobj(obj);
\r
805 // Since we can't guarantee uniqueness, check for an existing record.
\r
808 int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
\r
810 // Existing record, so we need to unmarshall it.
\r
811 istringstream in(record);
\r
819 if (!index || !*index)
\r
820 index = "_shibnull";
\r
821 DDF sessions = obj.addmember(index);
\r
822 if (!sessions.islist())
\r
824 DDF session = DDF(NULL).string(key);
\r
825 sessions.add(session);
\r
827 // Remarshall the record.
\r
831 // Try and store it back...
\r
833 ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
\r
835 // Out of sync, or went missing, so retry.
\r
836 return insert(key, expires, name, index);
\r
839 else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
\r
840 // Hit a dup, so just retry, hopefully hitting the other branch.
\r
841 return insert(key, expires, name, index);
\r
845 void SSCache::insert(
\r
846 const Application& application,
\r
847 const HTTPRequest& httpRequest,
\r
848 HTTPResponse& httpResponse,
\r
850 const saml2md::EntityDescriptor* issuer,
\r
851 const XMLCh* protocol,
\r
852 const saml2::NameID* nameid,
\r
853 const XMLCh* authn_instant,
\r
854 const XMLCh* session_index,
\r
855 const XMLCh* authncontext_class,
\r
856 const XMLCh* authncontext_decl,
\r
857 const vector<const Assertion*>* tokens,
\r
858 const vector<Attribute*>* attributes
\r
862 xmltooling::NDC ndc("insert");
\r
865 throw ConfigurationException("SessionCache insertion requires a StorageService.");
\r
867 m_log.debug("creating new session");
\r
869 time_t now = time(NULL);
\r
870 auto_ptr_char index(session_index);
\r
871 auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
\r
872 auto_ptr_char name(nameid ? nameid->getName() : NULL);
\r
875 // Check for a pending logout.
\r
876 if (strlen(name.get()) > 255)
\r
877 const_cast<char*>(name.get())[255] = 0;
\r
879 int ver = m_storage_lite->readText("Logout", name.get(), &pending);
\r
882 DDFJanitor jpend(pendobj);
\r
883 istringstream pstr(pending);
\r
885 // IdP.SP.index contains logout expiration, if any.
\r
886 DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getRelyingParty(issuer)->getString("entityID").second];
\r
887 const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
\r
888 if (!logexpstr && session_index) // we tried an exact session match, now try for NULL
\r
889 logexpstr = deadmenwalking["_shibnull"].string();
\r
891 auto_ptr_XMLCh dt(logexpstr);
\r
892 DateTime dtobj(dt.get());
\r
893 dtobj.parseDateTime();
\r
894 time_t logexp = dtobj.getEpoch();
\r
895 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
\r
896 throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
\r
901 auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
\r
903 // Store session properties in DDF.
\r
904 DDF obj = DDF(key.get()).structure();
\r
905 obj.addmember("version").integer(1);
\r
906 obj.addmember("application_id").string(application.getId());
\r
908 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
909 #ifndef HAVE_GMTIME_R
\r
910 struct tm* ptime=gmtime(&expires);
\r
913 struct tm* ptime=gmtime_r(&expires,&res);
\r
916 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
917 obj.addmember("expires").string(timebuf);
\r
919 obj.addmember("client_addr").string(httpRequest.getRemoteAddr().c_str());
\r
921 obj.addmember("entity_id").string(entity_id.get());
\r
923 auto_ptr_char prot(protocol);
\r
924 obj.addmember("protocol").string(prot.get());
\r
926 if (authn_instant) {
\r
927 auto_ptr_char instant(authn_instant);
\r
928 obj.addmember("authn_instant").string(instant.get());
\r
931 obj.addmember("session_index").string(index.get());
\r
932 if (authncontext_class) {
\r
933 auto_ptr_char ac(authncontext_class);
\r
934 obj.addmember("authncontext_class").string(ac.get());
\r
936 if (authncontext_decl) {
\r
937 auto_ptr_char ad(authncontext_decl);
\r
938 obj.addmember("authncontext_decl").string(ad.get());
\r
942 ostringstream namestr;
\r
943 namestr << *nameid;
\r
944 obj.addmember("nameid").string(namestr.str().c_str());
\r
948 obj.addmember("assertions").list();
\r
949 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
950 auto_ptr_char tokenid((*t)->getID());
\r
951 DDF tokid = DDF(NULL).string(tokenid.get());
\r
952 obj["assertions"].add(tokid);
\r
958 DDF attrlist = obj.addmember("attributes").list();
\r
959 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
\r
960 attr = (*a)->marshall();
\r
961 attrlist.add(attr);
\r
965 ostringstream record;
\r
968 m_log.debug("storing new session...");
\r
969 if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
\r
970 throw FatalProfileException("Attempted to create a session with a duplicate key.");
\r
972 // Store the reverse mapping for logout.
\r
975 insert(key.get(), expires, name.get(), index.get());
\r
977 catch (exception& ex) {
\r
978 m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
\r
983 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
\r
984 ostringstream tokenstr;
\r
986 auto_ptr_char tokenid((*t)->getID());
\r
987 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
\r
988 throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
\r
991 catch (exception& ex) {
\r
992 m_log.error("error storing assertion along with session: %s", ex.what());
\r
996 const char* pid = obj["entity_id"].string();
\r
997 const char* prot = obj["protocol"].string();
\r
998 m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
\r
999 key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
\r
1001 // Transaction Logging
\r
1002 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
1003 Locker locker(xlog);
\r
1004 xlog->log.infoStream() <<
\r
1005 "New session (ID: " <<
\r
1007 ") with (applicationId: " <<
\r
1008 application.getId() <<
\r
1009 ") for principal from (IdP: " <<
\r
1010 (pid ? pid : "none") <<
\r
1011 ") at (ClientAddress: " <<
\r
1012 httpRequest.getRemoteAddr() <<
\r
1013 ") with (NameIdentifier: " <<
\r
1014 (nameid ? name.get() : "none") <<
\r
1015 ") using (Protocol: " <<
\r
1016 (prot ? prot : "none") <<
\r
1020 xlog->log.infoStream() <<
\r
1021 "Cached the following attributes with session (ID: " <<
\r
1023 ") for (applicationId: " <<
\r
1024 application.getId() <<
\r
1026 for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
\r
1027 xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
\r
1028 xlog->log.info("}");
\r
1031 pair<string,const char*> shib_cookie = application.getCookieNameProps("_shibsession_");
\r
1032 string k(key.get());
\r
1033 k += shib_cookie.second;
\r
1034 httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
\r
1037 bool SSCache::matches(
\r
1038 const Application& application,
\r
1039 const xmltooling::HTTPRequest& request,
\r
1040 const saml2md::EntityDescriptor* issuer,
\r
1041 const saml2::NameID& nameid,
\r
1042 const set<string>* indexes
\r
1045 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
\r
1047 Session* session = find(application, request);
\r
1049 Locker locker(session, false);
\r
1050 if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
\r
1051 stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
\r
1052 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
\r
1056 catch (exception& ex) {
\r
1057 m_log.error("error while matching session: %s", ex.what());
\r
1062 vector<string>::size_type SSCache::logout(
\r
1063 const Application& application,
\r
1064 const saml2md::EntityDescriptor* issuer,
\r
1065 const saml2::NameID& nameid,
\r
1066 const set<string>* indexes,
\r
1068 vector<string>& sessionsKilled
\r
1072 xmltooling::NDC ndc("logout");
\r
1076 throw ConfigurationException("SessionCache insertion requires a StorageService.");
\r
1078 auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
\r
1079 auto_ptr_char name(nameid.getName());
\r
1081 m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
\r
1083 if (strlen(name.get()) > 255)
\r
1084 const_cast<char*>(name.get())[255] = 0;
\r
1087 DDFJanitor jobj(obj);
\r
1092 // Record the logout to prevent post-delivered assertions.
\r
1093 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
1094 #ifndef HAVE_GMTIME_R
\r
1095 struct tm* ptime=gmtime(&expires);
\r
1098 struct tm* ptime=gmtime_r(&expires,&res);
\r
1101 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
1103 time_t oldexp = 0;
\r
1104 ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
\r
1106 istringstream lin(record);
\r
1110 obj = DDF(NULL).structure();
\r
1113 // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
\r
1114 DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getRelyingParty(issuer)->getString("entityID").second);
\r
1116 for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
\r
1117 root.addmember(x->c_str()).string(timebuf);
\r
1120 root.addmember("_shibnull").string(timebuf);
\r
1124 ostringstream lout;
\r
1128 ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
\r
1130 // Out of sync, or went missing, so retry.
\r
1131 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
\r
1134 else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
\r
1135 // Hit a dup, so just retry, hopefully hitting the other branch.
\r
1136 return logout(application, issuer, nameid, indexes, expires, sessionsKilled);
\r
1143 // Read in potentially matching sessions.
\r
1144 ver = m_storage_lite->readText("NameID", name.get(), &record);
\r
1146 m_log.debug("no active sessions to logout for supplied issuer and subject");
\r
1150 istringstream in(record);
\r
1153 // The record contains child lists for each known session index.
\r
1155 DDF sessions = obj.first();
\r
1156 while (sessions.islist()) {
\r
1157 if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
\r
1158 key = sessions.first();
\r
1159 while (key.isstring()) {
\r
1160 // Fetch the session for comparison.
\r
1161 Session* session = NULL;
\r
1163 session = find(application, key.string());
\r
1165 catch (exception& ex) {
\r
1166 m_log.error("error locating session (%s): %s", key.string(), ex.what());
\r
1170 Locker locker(session, false);
\r
1172 if (XMLString::equals(session->getEntityID(), entityID.get())) {
\r
1174 if (stronglyMatches(issuer->getEntityID(), application.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
\r
1175 sessionsKilled.push_back(key.string());
\r
1179 m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
\r
1183 m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
\r
1187 // Session's gone, so...
\r
1188 sessionsKilled.push_back(key.string());
\r
1191 key = sessions.next();
\r
1194 // No sessions left for this index?
\r
1195 if (sessions.first().isnull())
\r
1196 sessions.destroy();
\r
1198 sessions = obj.next();
\r
1201 if (obj.first().isnull())
\r
1204 // If possible, write back the mapping record (this isn't crucial).
\r
1206 if (obj.isnull()) {
\r
1207 m_storage_lite->deleteText("NameID", name.get());
\r
1209 else if (!sessionsKilled.empty()) {
\r
1210 ostringstream out;
\r
1212 if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
\r
1213 m_log.warn("logout mapping record changed behind us, leaving it alone");
\r
1216 catch (exception& ex) {
\r
1217 m_log.error("error updating logout mapping record: %s", ex.what());
\r
1220 return sessionsKilled.size();
\r
1223 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
\r
1225 if (!XMLString::equals(n1.getName(), n2.getName()))
\r
1228 const XMLCh* s1 = n1.getFormat();
\r
1229 const XMLCh* s2 = n2.getFormat();
\r
1231 s1 = saml2::NameID::UNSPECIFIED;
\r
1233 s2 = saml2::NameID::UNSPECIFIED;
\r
1234 if (!XMLString::equals(s1,s2))
\r
1237 s1 = n1.getNameQualifier();
\r
1238 s2 = n2.getNameQualifier();
\r
1243 if (!XMLString::equals(s1,s2))
\r
1246 s1 = n1.getSPNameQualifier();
\r
1247 s2 = n2.getSPNameQualifier();
\r
1252 if (!XMLString::equals(s1,s2))
\r
1260 Session* SSCache::find(const Application& application, const char* key, const char* client_addr, time_t* timeout)
\r
1263 xmltooling::NDC ndc("find");
\r
1265 StoredSession* session=NULL;
\r
1268 m_log.debug("searching local cache for session (%s)", key);
\r
1270 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
\r
1271 if (i!=m_hashtable.end()) {
\r
1272 // Save off and lock the session.
\r
1273 session = i->second;
\r
1276 m_log.debug("session found locally, validating it for use");
\r
1284 if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
\r
1285 m_log.debug("session not found locally, remoting the search");
\r
1286 // Remote the request.
\r
1287 DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
\r
1288 DDFJanitor jin(in);
\r
1290 in.addmember("key").string(key);
\r
1291 in.addmember("application_id").string(application.getId());
\r
1292 if (timeout && *timeout) {
\r
1293 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
1294 #ifndef HAVE_GMTIME_R
\r
1295 struct tm* ptime=gmtime(timeout);
\r
1298 struct tm* ptime=gmtime_r(timeout,&res);
\r
1301 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
1302 in.addmember("timeout").string(timebuf);
\r
1306 out=application.getServiceProvider().getListenerService()->send(in);
\r
1307 if (!out.isstruct()) {
\r
1309 m_log.debug("session not found in remote cache");
\r
1313 // Wrap the results in a local entry and save it.
\r
1314 session = new StoredSession(this, out);
\r
1315 // The remote end has handled timeout issues, we handle address and expiration checks.
\r
1324 // We're out of process, so we can search the storage service directly.
\r
1325 #ifndef SHIBSP_LITE
\r
1327 throw ConfigurationException("SessionCache lookup requires a StorageService.");
\r
1329 m_log.debug("searching for session (%s)", key);
\r
1332 time_t lastAccess;
\r
1334 int ver = m_storage->readText(key, "session", &record, &lastAccess);
\r
1338 m_log.debug("reconstituting session and checking validity");
\r
1340 istringstream in(record);
\r
1343 lastAccess -= m_cacheTimeout; // adjusts it back to the last time the record's timestamp was touched
\r
1344 time_t now=time(NULL);
\r
1346 if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
\r
1347 m_log.info("session timed out (ID: %s)", key);
\r
1348 remove(application, key);
\r
1349 const char* eid = obj["entity_id"].string();
\r
1352 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1356 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
\r
1360 // Update storage expiration, if possible.
\r
1362 m_storage->updateContext(key, now + m_cacheTimeout);
\r
1364 catch (exception& ex) {
\r
1365 m_log.error("failed to update session expiration: %s", ex.what());
\r
1369 // Wrap the results in a local entry and save it.
\r
1370 session = new StoredSession(this, obj);
\r
1371 // We handled timeout issues, still need to handle address and expiration checks.
\r
1374 throw ConfigurationException("SessionCache search requires a StorageService.");
\r
1379 // Lock for writing and repeat the search to avoid duplication.
\r
1381 SharedLock shared(m_lock, false);
\r
1382 if (m_hashtable.count(key)) {
\r
1383 // We're using an existing session entry.
\r
1385 session = m_hashtable[key];
\r
1389 m_hashtable[key]=session;
\r
1395 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
\r
1396 m_log.error("an application (%s) tried to access another application's session", application.getId());
\r
1397 session->unlock();
\r
1401 // Verify currency and update the timestamp if indicated by caller.
\r
1403 session->validate(application, client_addr, timeout);
\r
1406 session->unlock();
\r
1407 remove(application, key);
\r
1414 void SSCache::remove(const Application& application, const char* key)
\r
1417 xmltooling::NDC ndc("remove");
\r
1419 // Take care of local copy.
\r
1423 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
\r
1424 // Remove the session from storage directly.
\r
1425 #ifndef SHIBSP_LITE
\r
1426 m_storage->deleteContext(key);
\r
1427 m_log.info("removed session (%s)", key);
\r
1429 TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
\r
1430 Locker locker(xlog);
\r
1431 xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
\r
1433 throw ConfigurationException("SessionCache removal requires a StorageService.");
\r
1437 // Remote the request.
\r
1438 DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
\r
1439 DDFJanitor jin(in);
\r
1441 in.addmember("key").string(key);
\r
1442 in.addmember("application_id").string(application.getId());
\r
1444 DDF out = application.getServiceProvider().getListenerService()->send(in);
\r
1449 void SSCache::dormant(const char* key)
\r
1452 xmltooling::NDC ndc("dormant");
\r
1455 m_log.debug("deleting local copy of session (%s)", key);
\r
1457 // lock the cache for writing, which means we know nobody is sitting in find()
\r
1460 // grab the entry from the table
\r
1461 map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
\r
1462 if (i==m_hashtable.end()) {
\r
1467 // ok, remove the entry and lock it
\r
1468 StoredSession* entry=i->second;
\r
1469 m_hashtable.erase(key);
\r
1472 // unlock the cache
\r
1475 // we can release the cache entry lock because we know we're not in the cache anymore
\r
1481 void SSCache::cleanup()
\r
1484 xmltooling::NDC ndc("cleanup");
\r
1487 Mutex* mutex = Mutex::create();
\r
1489 // Load our configuration details...
\r
1490 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
\r
1491 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
\r
1492 int rerun_timer = 900;
\r
1494 rerun_timer = XMLString::parseInt(tag);
\r
1495 if (rerun_timer <= 0)
\r
1496 rerun_timer = 900;
\r
1500 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_inprocTimeout);
\r
1502 while (!shutdown) {
\r
1503 shutdown_wait->timedwait(mutex,rerun_timer);
\r
1507 // Ok, let's run through the cleanup process and clean out
\r
1508 // really old sessions. This is a two-pass process. The
\r
1509 // first pass is done holding a read-lock while we iterate over
\r
1510 // the cache. The second pass doesn't need a lock because
\r
1511 // the 'deletes' will lock the cache.
\r
1513 // Pass 1: iterate over the map and find all entries that have not been
\r
1514 // used in the allotted timeout.
\r
1515 vector<string> stale_keys;
\r
1516 time_t stale = time(NULL) - m_inprocTimeout;
\r
1518 m_log.debug("cleanup thread running");
\r
1521 for (map<string,StoredSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
\r
1522 // If the last access was BEFORE the stale timeout...
\r
1523 i->second->lock();
\r
1524 time_t last=i->second->getLastAccess();
\r
1525 i->second->unlock();
\r
1527 stale_keys.push_back(i->first);
\r
1531 if (!stale_keys.empty()) {
\r
1532 m_log.info("purging %d old sessions", stale_keys.size());
\r
1534 // Pass 2: walk through the list of stale entries and remove them from the cache
\r
1535 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
\r
1536 dormant(j->c_str());
\r
1539 m_log.debug("cleanup thread completed");
\r
1542 m_log.info("cleanup thread exiting");
\r
1546 Thread::exit(NULL);
\r
1549 void* SSCache::cleanup_fn(void* cache_p)
\r
1552 // First, let's block all signals
\r
1553 Thread::mask_all_signals();
\r
1556 // Now run the cleanup process.
\r
1557 reinterpret_cast<SSCache*>(cache_p)->cleanup();
\r
1561 #ifndef SHIBSP_LITE
\r
1563 void SSCache::receive(DDF& in, ostream& out)
\r
1566 xmltooling::NDC ndc("receive");
\r
1569 if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
\r
1570 const char* key=in["key"].string();
\r
1572 throw ListenerException("Required parameters missing for session lookup.");
\r
1574 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
1576 throw ListenerException("Application not found, check configuration?");
\r
1578 // Do an unversioned read.
\r
1580 time_t lastAccess;
\r
1581 if (!m_storage->readText(key, "session", &record, &lastAccess)) {
\r
1583 DDFJanitor jan(ret);
\r
1588 // Adjust for expiration to recover last access time and check timeout.
\r
1589 lastAccess -= m_cacheTimeout;
\r
1590 time_t now=time(NULL);
\r
1592 // See if we need to check for a timeout.
\r
1593 if (in["timeout"].string()) {
\r
1594 time_t timeout = 0;
\r
1595 auto_ptr_XMLCh dt(in["timeout"].string());
\r
1596 DateTime dtobj(dt.get());
\r
1597 dtobj.parseDateTime();
\r
1598 timeout = dtobj.getEpoch();
\r
1600 if (timeout > 0 && now - lastAccess >= timeout) {
\r
1601 m_log.info("session timed out (ID: %s)", key);
\r
1602 remove(*app, key);
\r
1603 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1606 // Update storage expiration, if possible.
\r
1608 m_storage->updateContext(key, now + m_cacheTimeout);
\r
1610 catch (exception& ex) {
\r
1611 m_log.error("failed to update session expiration: %s", ex.what());
\r
1615 // Send the record back.
\r
1618 else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
\r
1619 const char* key=in["key"].string();
\r
1621 throw ListenerException("Required parameters missing for session check.");
\r
1623 // Do a versioned read.
\r
1625 time_t lastAccess;
\r
1626 int curver = in["version"].integer();
\r
1627 int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
\r
1629 m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
\r
1630 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1633 // Adjust for expiration to recover last access time and check timeout.
\r
1634 lastAccess -= m_cacheTimeout;
\r
1635 time_t now=time(NULL);
\r
1637 // See if we need to check for a timeout.
\r
1638 time_t timeout = 0;
\r
1639 auto_ptr_XMLCh dt(in["timeout"].string());
\r
1641 DateTime dtobj(dt.get());
\r
1642 dtobj.parseDateTime();
\r
1643 timeout = dtobj.getEpoch();
\r
1646 if (timeout > 0 && now - lastAccess >= timeout) {
\r
1647 m_log.info("session timed out (ID: %s)", key);
\r
1648 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
1651 // Update storage expiration, if possible.
\r
1653 m_storage->updateContext(key, now + m_cacheTimeout);
\r
1655 catch (exception& ex) {
\r
1656 m_log.error("failed to update session expiration: %s", ex.what());
\r
1659 if (ver > curver) {
\r
1660 // Send the record back.
\r
1665 DDFJanitor jan(ret);
\r
1669 else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
\r
1670 const char* key=in["key"].string();
\r
1672 throw ListenerException("Required parameter missing for session removal.");
\r
1674 const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
\r
1676 throw ConfigurationException("Application not found, check configuration?");
\r
1678 remove(*app, key);
\r
1680 DDFJanitor jan(ret);
\r