Add a redundant safety check to insert
[shibboleth/cpp-sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * StorageServiceSessionCache.cpp
23  *
24  * StorageService-based SessionCache implementation.
25  *
26  * Instead of optimizing this plugin with a buffering scheme that keeps objects around
27  * and avoids extra parsing steps, I'm assuming that systems that require such can
28  * layer their own cache plugin on top of this version either by delegating to it
29  * or using the remoting support. So this version will load sessions directly
30  * from the StorageService, instantiate enough to expose the Session API,
31  * and then delete everything when they're unlocked. All data in memory is always
32  * kept in sync with the StorageService (no lazy updates).
33  */
34
35 #include "internal.h"
36 #include "Application.h"
37 #include "exceptions.h"
38 #include "ServiceProvider.h"
39 #include "SessionCacheEx.h"
40 #include "TransactionLog.h"
41 #include "attribute/Attribute.h"
42 #include "handler/RemotedHandler.h"
43 #include "remoting/ListenerService.h"
44 #include "util/SPConstants.h"
45
46 #include <algorithm>
47 #include <boost/bind.hpp>
48 #include <boost/shared_ptr.hpp>
49 #include <xmltooling/io/HTTPRequest.h>
50 #include <xmltooling/io/HTTPResponse.h>
51 #include <xmltooling/util/DateTime.h>
52 #include <xmltooling/util/NDC.h>
53 #include <xmltooling/util/ParserPool.h>
54 #include <xmltooling/util/Threads.h>
55 #include <xmltooling/util/XMLHelper.h>
56 #include <xercesc/util/XMLUniDefs.hpp>
57
58 #ifndef SHIBSP_LITE
59 # include <saml/exceptions.h>
60 # include <saml/SAMLConfig.h>
61 # include <saml/saml2/core/Assertions.h>
62 # include <saml/saml2/metadata/Metadata.h>
63 # include <xmltooling/XMLToolingConfig.h>
64 # include <xmltooling/util/StorageService.h>
65 # include <xercesc/util/XMLStringTokenizer.hpp>
66 using namespace opensaml::saml2md;
67 #else
68 # include <ctime>
69 # include <xmltooling/util/DateTime.h>
70 #endif
71
72 using namespace shibsp;
73 using namespace opensaml;
74 using namespace xmltooling;
75 using namespace boost;
76 using namespace std;
77
78 namespace {
79
80     // Allows the cache to bind sessions to multiple client address
81     // families based on whatever this function returns.
82     static const char* getAddressFamily(const char* addr) {
83         if (strchr(addr, ':'))
84             return "6";
85         else
86             return "4";
87     }
88
89     class StoredSession;
90     class SSCache : public SessionCacheEx
91 #ifndef SHIBSP_LITE
92         ,public virtual Remoted
93 #endif
94     {
95     public:
96         SSCache(const DOMElement* e);
97         virtual ~SSCache();
98
99 #ifndef SHIBSP_LITE
100         void receive(DDF& in, ostream& out);
101
102         void insert(
103             const Application& app,
104             const HTTPRequest& httpRequest,
105             HTTPResponse& httpResponse,
106             time_t expires,
107             const EntityDescriptor* issuer=nullptr,
108             const XMLCh* protocol=nullptr,
109             const saml2::NameID* nameid=nullptr,
110             const XMLCh* authn_instant=nullptr,
111             const XMLCh* session_index=nullptr,
112             const XMLCh* authncontext_class=nullptr,
113             const XMLCh* authncontext_decl=nullptr,
114             const vector<const Assertion*>* tokens=nullptr,
115             const vector<Attribute*>* attributes=nullptr
116             ) {
117             string dummy;
118             insert(dummy, app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
119                     authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
120         }
121
122         void insert(
123             string& sessionID,
124             const Application& app,
125             const HTTPRequest& httpRequest,
126             HTTPResponse& httpResponse,
127             time_t expires,
128             const EntityDescriptor* issuer=nullptr,
129             const XMLCh* protocol=nullptr,
130             const saml2::NameID* nameid=nullptr,
131             const XMLCh* authn_instant=nullptr,
132             const XMLCh* session_index=nullptr,
133             const XMLCh* authncontext_class=nullptr,
134             const XMLCh* authncontext_decl=nullptr,
135             const vector<const Assertion*>* tokens=nullptr,
136             const vector<Attribute*>* attributes=nullptr
137             );
138         vector<string>::size_type logout(
139             const Application& app,
140             const EntityDescriptor* issuer,
141             const saml2::NameID& nameid,
142             const set<string>* indexes,
143             time_t expires,
144             vector<string>& sessions
145             ) {
146             return _logout(app, issuer, nameid, indexes, expires, sessions, 0);
147         }
148         bool matches(
149             const Application& app,
150             const HTTPRequest& request,
151             const EntityDescriptor* issuer,
152             const saml2::NameID& nameid,
153             const set<string>* indexes
154             );
155 #endif
156         Session* find(const Application& app, const char* key, const char* client_addr=nullptr, time_t* timeout=nullptr);
157         void remove(const Application& app, const char* key);
158         void test();
159
160         string active(const Application& app, const HTTPRequest& request) {
161             if (!m_inboundHeader.empty()) {
162                 string session_id = request.getHeader(m_inboundHeader.c_str());
163                 if (!session_id.empty())
164                     return session_id;
165             }
166             pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
167             const char* session_id = request.getCookie(shib_cookie.first.c_str());
168             return (session_id ? session_id : "");
169         }
170
171         Session* find(const Application& app, const HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr) {
172             string id = active(app, request);
173             if (!id.empty())
174                 return find(app, id.c_str(), client_addr, timeout);
175             return nullptr;
176         }
177
178         Session* find(const Application& app, HTTPRequest& request, const char* client_addr=nullptr, time_t* timeout=nullptr);
179         void remove(const Application& app, const HTTPRequest& request, HTTPResponse* response=nullptr);
180
181         unsigned long getCacheTimeout(const Application& app) {
182             // Computes offset for adjusting expiration of sessions.
183             // This can either be static, or dynamic based on the per-app session timeout or lifetime.
184             if (m_cacheTimeout)
185                 return m_cacheTimeout;
186             pair<bool,unsigned int> timeout = pair<bool,unsigned int>(false, 3600);
187             const PropertySet* props = app.getPropertySet("Sessions");
188             if (props) {
189                 timeout = props->getUnsignedInt("timeout");
190                 if (!timeout.first)
191                     timeout.second = 3600;
192             }
193             // As long as one of the two factors is set, add them together.
194             if (timeout.second > 0 || m_cacheAllowance > 0)
195                 return timeout.second + m_cacheAllowance;
196
197             // If timeouts are off, and there's no cache slop set, then use the lifetime.
198             timeout = pair<bool,unsigned int>(false, 28800);
199             if (props) {
200                 timeout = props->getUnsignedInt("lifetime");
201                 if (!timeout.first || timeout.second == 0)
202                     timeout.second = 28800;
203             }
204             return timeout.second;
205         }
206
207         Category& m_log;
208         bool inproc;
209 #ifndef SHIBSP_LITE
210         StorageService* m_storage;
211         StorageService* m_storage_lite;
212 #endif
213
214     private:
215 #ifndef SHIBSP_LITE
216         // maintain back-mappings of NameID/SessionIndex -> session key
217         void insert(const char* key, time_t expires, const char* name, const char* index, short attempts=0);
218         vector<string>::size_type _logout(
219             const Application& app,
220             const EntityDescriptor* issuer,
221             const saml2::NameID& nameid,
222             const set<string>* indexes,
223             time_t expires,
224             vector<string>& sessions,
225             short attempts
226             );
227         bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
228         LogoutEvent* newLogoutEvent(const Application& app) const;
229
230         bool m_cacheAssertions,m_reverseIndex;
231         set<xstring> m_excludedNames;
232 #endif
233         const DOMElement* m_root;         // Only valid during initialization
234         unsigned long m_inprocTimeout,m_cacheTimeout,m_cacheAllowance;
235         string m_inboundHeader,m_outboundHeader;
236
237         // inproc means we buffer sessions in memory
238         scoped_ptr<RWLock> m_lock;
239         map<string,StoredSession*> m_hashtable;
240
241         // management of buffered sessions
242         void dormant(const char* key);
243         static void* cleanup_fn(void*);
244
245         bool shutdown;
246         scoped_ptr<CondWait> shutdown_wait;
247         scoped_ptr<Thread> cleanup_thread;
248     };
249
250     class StoredSession : public virtual Session
251     {
252     public:
253         StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_cache(cache), m_expires(0), m_lastAccess(time(nullptr)) {
254             // Check for old address format.
255             if (m_obj["client_addr"].isstring()) {
256                 const char* saddr = m_obj["client_addr"].string();
257                 DDF addrobj = m_obj["client_addr"].structure();
258                 if (saddr && *saddr) {
259                     addrobj.addmember(getAddressFamily(saddr)).string(saddr);
260                 }
261             }
262
263             auto_ptr_XMLCh exp(m_obj["expires"].string());
264             if (exp.get()) {
265                 DateTime iso(exp.get());
266                 iso.parseDateTime();
267                 m_expires = iso.getEpoch();
268             }
269
270 #ifndef SHIBSP_LITE
271             const char* nameid = obj["nameid"].string();
272             if (nameid) {
273                 // Parse and bind the document into an XMLObject.
274                 istringstream instr(nameid);
275                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
276                 XercesJanitor<DOMDocument> janitor(doc);
277                 m_nameid.reset(saml2::NameIDBuilder::buildNameID());
278                 m_nameid->unmarshall(doc->getDocumentElement(), true);
279                 janitor.release();
280             }
281 #endif
282             if (cache->inproc)
283                 m_lock.reset(Mutex::create());
284         }
285
286         ~StoredSession() {
287             m_obj.destroy();
288             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
289         }
290
291         Lockable* lock() {
292             if (m_lock.get())
293                 m_lock->lock();
294             return this;
295         }
296         void unlock() {
297             if (m_lock.get())
298                 m_lock->unlock();
299             else
300                 delete this;
301         }
302
303         const char* getID() const {
304             return m_obj.name();
305         }
306         const char* getApplicationID() const {
307             return m_obj["application_id"].string();
308         }
309         const char* getClientAddress() const {
310             return m_obj["client_addr"].first().string();
311         }
312
313         const char* getClientAddress(const char* family) const {
314             if (family)
315                 return m_obj["client_addr"][family].string();
316             return nullptr;
317         }
318         void setClientAddress(const char* client_addr) {
319             DDF obj = m_obj["client_addr"];
320             if (!obj.isstruct())
321                 obj = m_obj.addmember("client_addr").structure();
322             obj.addmember(getAddressFamily(client_addr)).string(client_addr);
323         }
324
325         const char* getEntityID() const {
326             return m_obj["entity_id"].string();
327         }
328         const char* getProtocol() const {
329             return m_obj["protocol"].string();
330         }
331         const char* getAuthnInstant() const {
332             return m_obj["authn_instant"].string();
333         }
334 #ifndef SHIBSP_LITE
335         const saml2::NameID* getNameID() const {
336             return m_nameid.get();
337         }
338 #endif
339         const char* getSessionIndex() const {
340             return m_obj["session_index"].string();
341         }
342         const char* getAuthnContextClassRef() const {
343             return m_obj["authncontext_class"].string();
344         }
345         const char* getAuthnContextDeclRef() const {
346             return m_obj["authncontext_decl"].string();
347         }
348         const vector<Attribute*>& getAttributes() const {
349             if (m_attributes.empty())
350                 unmarshallAttributes();
351             return m_attributes;
352         }
353         const multimap<string,const Attribute*>& getIndexedAttributes() const {
354             if (m_attributeIndex.empty()) {
355                 if (m_attributes.empty())
356                     unmarshallAttributes();
357                 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
358                     const vector<string>& aliases = (*a)->getAliases();
359                     for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
360                         m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
361                 }
362             }
363             return m_attributeIndex;
364         }
365         const vector<const char*>& getAssertionIDs() const {
366             if (m_ids.empty()) {
367                 DDF ids = m_obj["assertions"];
368                 DDF id = ids.first();
369                 while (id.isstring()) {
370                     m_ids.push_back(id.string());
371                     id = ids.next();
372                 }
373             }
374             return m_ids;
375         }
376
377         void validate(const Application& application, const char* client_addr, time_t* timeout);
378
379 #ifndef SHIBSP_LITE
380         void addAttributes(const vector<Attribute*>& attributes);
381         const Assertion* getAssertion(const char* id) const;
382         void addAssertion(Assertion* assertion);
383 #endif
384
385         time_t getExpiration() const { return m_expires; }
386         time_t getLastAccess() const { return m_lastAccess; }
387
388     private:
389         void unmarshallAttributes() const;
390
391         DDF m_obj;
392 #ifndef SHIBSP_LITE
393         scoped_ptr<saml2::NameID> m_nameid;
394         mutable map< string,boost::shared_ptr<Assertion> > m_tokens;
395 #endif
396         mutable vector<Attribute*> m_attributes;
397         mutable multimap<string,const Attribute*> m_attributeIndex;
398         mutable vector<const char*> m_ids;
399
400         SSCache* m_cache;
401         time_t m_expires,m_lastAccess;
402         scoped_ptr<Mutex> m_lock;
403     };
404
405     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
406     {
407         return new SSCache(e);
408     }
409 }
410
411 Session* SessionCache::find(const Application& application, HTTPRequest& request, const char* client_addr, time_t* timeout)
412 {
413     return find(application, const_cast<const HTTPRequest&>(request), client_addr, timeout);
414 }
415
416 void SHIBSP_API shibsp::registerSessionCaches()
417 {
418     SPConfig::getConfig().SessionCacheManager.registerFactory(STORAGESERVICE_SESSION_CACHE, StorageServiceCacheFactory);
419 }
420
421 Session::Session()
422 {
423 }
424
425 Session::~Session()
426 {
427 }
428
429 void StoredSession::unmarshallAttributes() const
430 {
431     Attribute* attribute;
432     DDF attrs = m_obj["attributes"];
433     DDF attr = attrs.first();
434     while (!attr.isnull()) {
435         try {
436             attribute = Attribute::unmarshall(attr);
437             m_attributes.push_back(attribute);
438             if (m_cache->m_log.isDebugEnabled())
439                 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
440                     attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
441         }
442         catch (AttributeException& ex) {
443             const char* id = attr.first().name();
444             m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
445         }
446         attr = attrs.next();
447     }
448 }
449
450 void StoredSession::validate(const Application& app, const char* client_addr, time_t* timeout)
451 {
452     time_t now = time(nullptr);
453
454     // Basic expiration?
455     if (m_expires > 0) {
456         if (now > m_expires) {
457             m_cache->m_log.info("session expired (ID: %s)", getID());
458             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
459         }
460     }
461
462     // Address check?
463     if (client_addr) {
464         const char* saddr = getClientAddress(getAddressFamily(client_addr));
465         if (saddr && *saddr) {
466             if (!XMLString::equals(saddr, client_addr)) {
467                 m_cache->m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
468                 throw RetryableProfileException(
469                     "Your IP address ($1) does not match the address recorded at the time the session was established.",
470                     params(1, client_addr)
471                     );
472             }
473             client_addr = nullptr;  // clear out parameter as signal that session need not be updated below
474         }
475         else {
476             m_cache->m_log.info("session (%s) not yet bound to client address type, binding it to (%s)", getID(), client_addr);
477         }
478     }
479
480     if (!timeout && !client_addr)
481         return;
482
483     if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
484         DDF in("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
485         DDFJanitor jin(in);
486         in.structure();
487         in.addmember("key").string(getID());
488         in.addmember("version").integer(m_obj["version"].integer());
489         in.addmember("application_id").string(app.getId());
490         if (client_addr)    // signals we need to bind an additional address to the session
491             in.addmember("client_addr").string(client_addr);
492         if (timeout && *timeout) {
493             // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
494 #ifndef HAVE_GMTIME_R
495             struct tm* ptime = gmtime(timeout);
496 #else
497             struct tm res;
498             struct tm* ptime = gmtime_r(timeout,&res);
499 #endif
500             char timebuf[32];
501             strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
502             in.addmember("timeout").string(timebuf);
503         }
504
505         try {
506             out=app.getServiceProvider().getListenerService()->send(in);
507         }
508         catch (...) {
509             out.destroy();
510             throw;
511         }
512
513         if (out.isstruct()) {
514             // We got an updated record back.
515             m_cache->m_log.debug("session updated, reconstituting it");
516             m_ids.clear();
517             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
518             m_attributes.clear();
519             m_attributeIndex.clear();
520             m_obj.destroy();
521             m_obj = out;
522         }
523     }
524     else {
525 #ifndef SHIBSP_LITE
526         if (!m_cache->m_storage)
527             throw ConfigurationException("Session touch requires a StorageService.");
528
529         // Versioned read, since we already have the data in hand if it's current.
530         string record;
531         time_t lastAccess;
532         int curver = m_obj["version"].integer();
533         int ver = m_cache->m_storage->readText(getID(), "session", &record, &lastAccess, curver);
534         if (ver == 0) {
535             m_cache->m_log.warn("unsuccessful versioned read of session (ID: %s), cache out of sync?", getID());
536             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
537         }
538
539         if (timeout) {
540             // Adjust for expiration to recover last access time and check timeout.
541             unsigned long cacheTimeout = m_cache->getCacheTimeout(app);
542             lastAccess -= cacheTimeout;
543             if (*timeout > 0 && now - lastAccess >= *timeout) {
544                 m_cache->m_log.info("session timed out (ID: %s)", getID());
545                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
546             }
547
548             // Update storage expiration, if possible.
549             try {
550                 m_cache->m_storage->updateContext(getID(), now + cacheTimeout);
551             }
552             catch (std::exception& ex) {
553                 m_cache->m_log.error("failed to update session expiration: %s", ex.what());
554             }
555         }
556
557         if (ver > curver) {
558             // We got an updated record back.
559             DDF newobj;
560             istringstream in(record);
561             in >> newobj;
562             m_ids.clear();
563             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
564             m_attributes.clear();
565             m_attributeIndex.clear();
566             m_obj.destroy();
567             m_obj = newobj;
568         }
569
570         // We may need to write back a new address into the session using a versioned update loop.
571         if (client_addr) {
572             short attempts = 0;
573             do {
574                 const char* saddr = getClientAddress(getAddressFamily(client_addr));
575                 if (saddr) {
576                     // Something snuck in and bound the session to this address type, so it better match what we have.
577                     if (!XMLString::equals(saddr, client_addr)) {
578                         m_cache->m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
579                         throw RetryableProfileException(
580                             "Your IP address ($1) does not match the address recorded at the time the session was established.",
581                             params(1, client_addr)
582                             );
583                     }
584                     break;  // No need to update.
585                 }
586                 else {
587                     // Bind it into the session.
588                     setClientAddress(client_addr);
589                 }
590
591                 // Tentatively increment the version.
592                 m_obj["version"].integer(m_obj["version"].integer() + 1);
593
594                 ostringstream str;
595                 str << m_obj;
596                 record = str.str();
597
598                 try {
599                     ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer() - 1);
600                 }
601                 catch (std::exception&) {
602                     m_obj["version"].integer(m_obj["version"].integer() - 1);
603                     throw;
604                 }
605
606                 if (ver <= 0) {
607                     m_obj["version"].integer(m_obj["version"].integer() - 1);
608                 }
609
610                 if (!ver) {
611                     // Fatal problem with update.
612                     m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
613                     throw IOException("Unable to update stored session.");
614                 }
615                 else if (ver < 0) {
616                     // Out of sync.
617                     if (++attempts > 10) {
618                         m_cache->m_log.error("failed to bind client address, update attempts exceeded limit");
619                         throw IOException("Unable to update stored session, exceeded retry limit.");
620                     }
621                     m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
622                     ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
623                     if (!ver) {
624                         m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
625                         throw IOException("Unable to read back stored session.");
626                     }
627
628                     // Reset object.
629                     DDF newobj;
630                     istringstream in(record);
631                     in >> newobj;
632
633                     m_ids.clear();
634                     for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
635                     m_attributes.clear();
636                     m_attributeIndex.clear();
637                     newobj["version"].integer(ver);
638                     m_obj.destroy();
639                     m_obj = newobj;
640
641                     ver = -1;
642                 }
643             } while (ver < 0); // negative indicates a sync issue so we retry
644         }
645 #else
646         throw ConfigurationException("Session touch requires a StorageService.");
647 #endif
648     }
649
650     m_lastAccess = now;
651 }
652
653 #ifndef SHIBSP_LITE
654
655 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
656 {
657 #ifdef _DEBUG
658     xmltooling::NDC ndc("addAttributes");
659 #endif
660
661     if (!m_cache->m_storage)
662         throw ConfigurationException("Session modification requires a StorageService.");
663
664     m_cache->m_log.debug("adding attributes to session (%s)", getID());
665
666     int ver;
667     short attempts = 0;
668     do {
669         DDF attr;
670         DDF attrs = m_obj["attributes"];
671         if (!attrs.islist())
672             attrs = m_obj.addmember("attributes").list();
673         for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
674             attr = (*a)->marshall();
675             attrs.add(attr);
676         }
677
678         // Tentatively increment the version.
679         m_obj["version"].integer(m_obj["version"].integer()+1);
680
681         ostringstream str;
682         str << m_obj;
683         string record(str.str());
684
685         try {
686             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
687         }
688         catch (std::exception&) {
689             // Roll back modification to record.
690             m_obj["version"].integer(m_obj["version"].integer()-1);
691             vector<Attribute*>::size_type count = attributes.size();
692             while (count--)
693                 attrs.last().destroy();
694             throw;
695         }
696
697         if (ver <= 0) {
698             // Roll back modification to record.
699             m_obj["version"].integer(m_obj["version"].integer()-1);
700             vector<Attribute*>::size_type count = attributes.size();
701             while (count--)
702                 attrs.last().destroy();
703         }
704         if (!ver) {
705             // Fatal problem with update.
706             throw IOException("Unable to update stored session.");
707         }
708         else if (ver < 0) {
709             // Out of sync.
710             if (++attempts > 10) {
711                 m_cache->m_log.error("failed to update stored session, update attempts exceeded limit");
712                 throw IOException("Unable to update stored session, exceeded retry limit.");
713             }
714             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
715             ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
716             if (!ver) {
717                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
718                 throw IOException("Unable to read back stored session.");
719             }
720
721             // Reset object.
722             DDF newobj;
723             istringstream in(record);
724             in >> newobj;
725
726             m_ids.clear();
727             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
728             m_attributes.clear();
729             m_attributeIndex.clear();
730             newobj["version"].integer(ver);
731             m_obj.destroy();
732             m_obj = newobj;
733
734             ver = -1;
735         }
736     } while (ver < 0);  // negative indicates a sync issue so we retry
737
738     // We own them now, so clean them up.
739     for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
740 }
741
742 const Assertion* StoredSession::getAssertion(const char* id) const
743 {
744     if (!m_cache->m_storage)
745         throw ConfigurationException("Assertion retrieval requires a StorageService.");
746
747     map< string,boost::shared_ptr<Assertion> >::const_iterator i = m_tokens.find(id);
748     if (i != m_tokens.end())
749         return i->second.get();
750
751     string tokenstr;
752     if (!m_cache->m_storage->readText(getID(), id, &tokenstr, nullptr))
753         throw FatalProfileException("Assertion not found in cache.");
754
755     // Parse and bind the document into an XMLObject.
756     istringstream instr(tokenstr);
757     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
758     XercesJanitor<DOMDocument> janitor(doc);
759     boost::shared_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
760     janitor.release();
761     
762     boost::shared_ptr<Assertion> token = dynamic_pointer_cast<Assertion,XMLObject>(xmlObject);
763     if (!token)
764         throw FatalProfileException("Request for cached assertion returned an unknown object type.");
765
766     m_tokens[id] = token;
767     return token.get();
768 }
769
770 void StoredSession::addAssertion(Assertion* assertion)
771 {
772 #ifdef _DEBUG
773     xmltooling::NDC ndc("addAssertion");
774 #endif
775
776     if (!m_cache->m_storage)
777         throw ConfigurationException("Session modification requires a StorageService.");
778     else if (!assertion)
779         throw FatalProfileException("Unknown object type passed to session for storage.");
780
781     auto_ptr_char id(assertion->getID());
782     if (!id.get() || !*id.get())
783         throw IOException("Assertion did not carry an ID.");
784     else if (strlen(id.get()) > m_cache->m_storage->getCapabilities().getKeySize())
785         throw IOException("Assertion ID ($1) exceeds allowable storage key size.", params(1, id.get()));
786
787     m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
788
789     time_t exp;
790     if (!m_cache->m_storage->readText(getID(), "session", nullptr, &exp))
791         throw IOException("Unable to load expiration time for stored session.");
792
793     ostringstream tokenstr;
794     tokenstr << *assertion;
795     if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
796         throw IOException("Attempted to insert duplicate assertion ID into session.");
797
798     int ver;
799     short attempts = 0;
800     do {
801         DDF token = DDF(nullptr).string(id.get());
802         m_obj["assertions"].add(token);
803
804         // Tentatively increment the version.
805         m_obj["version"].integer(m_obj["version"].integer() + 1);
806
807         ostringstream str;
808         str << m_obj;
809         string record(str.str());
810
811         try {
812             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
813         }
814         catch (std::exception&) {
815             token.destroy();
816             m_obj["version"].integer(m_obj["version"].integer() - 1);
817             m_cache->m_storage->deleteText(getID(), id.get());
818             throw;
819         }
820
821         if (ver <= 0) {
822             token.destroy();
823             m_obj["version"].integer(m_obj["version"].integer()-1);
824         }
825         if (!ver) {
826             // Fatal problem with update.
827             m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
828             m_cache->m_storage->deleteText(getID(), id.get());
829             throw IOException("Unable to update stored session.");
830         }
831         else if (ver < 0) {
832             // Out of sync.
833             if (++attempts > 10) {
834                 m_cache->m_log.error("failed to update stored session, update attempts exceeded limit");
835                 throw IOException("Unable to update stored session, exceeded retry limit.");
836             }
837             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
838             ver = m_cache->m_storage->readText(getID(), "session", &record, nullptr);
839             if (!ver) {
840                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
841                 m_cache->m_storage->deleteText(getID(), id.get());
842                 throw IOException("Unable to read back stored session.");
843             }
844
845             // Reset object.
846             DDF newobj;
847             istringstream in(record);
848             in >> newobj;
849
850             m_ids.clear();
851             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
852             m_attributes.clear();
853             m_attributeIndex.clear();
854             newobj["version"].integer(ver);
855             m_obj.destroy();
856             m_obj = newobj;
857
858             ver = -1;
859         }
860     } while (ver < 0); // negative indicates a sync issue so we retry
861
862     m_ids.clear();
863     delete assertion;
864 }
865
866 #endif
867
868 SessionCache::SessionCache()
869 {
870 }
871
872 SessionCache::~SessionCache()
873 {
874 }
875
876 #ifndef SHIBSP_LITE
877
878 void SessionCache::insert(
879     string& sessionID,
880     const Application& app,
881     const HTTPRequest& httpRequest,
882     HTTPResponse& httpResponse,
883     time_t expires,
884     const EntityDescriptor* issuer,
885     const XMLCh* protocol,
886     const saml2::NameID* nameid,
887     const XMLCh* authn_instant,
888     const XMLCh* session_index,
889     const XMLCh* authncontext_class,
890     const XMLCh* authncontext_decl,
891     const vector<const Assertion*>* tokens,
892     const vector<Attribute*>* attributes
893     ) {
894     return insert(app, httpRequest, httpResponse, expires, issuer, protocol, nameid,
895             authn_instant, session_index, authncontext_class, authncontext_decl, tokens, attributes);
896 }
897
898 #endif
899
900 SessionCacheEx::SessionCacheEx()
901 {
902 }
903
904 SessionCacheEx::~SessionCacheEx()
905 {
906 }
907
908 SSCache::SSCache(const DOMElement* e)
909     : m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), inproc(true),
910 #ifndef SHIBSP_LITE
911       m_storage(nullptr), m_storage_lite(nullptr), m_cacheAssertions(true), m_reverseIndex(true),
912 #endif
913       m_root(e), m_inprocTimeout(900), m_cacheTimeout(0), m_cacheAllowance(0), shutdown(false)
914 {
915     SPConfig& conf = SPConfig::getConfig();
916     inproc = conf.isEnabled(SPConfig::InProcess);
917
918     static const XMLCh cacheAllowance[] =       UNICODE_LITERAL_14(c,a,c,h,e,A,l,l,o,w,a,n,c,e);
919     static const XMLCh cacheAssertions[] =      UNICODE_LITERAL_15(c,a,c,h,e,A,s,s,e,r,t,i,o,n,s);
920     static const XMLCh cacheTimeout[] =         UNICODE_LITERAL_12(c,a,c,h,e,T,i,m,e,o,u,t);
921     static const XMLCh excludeReverseIndex[] =  UNICODE_LITERAL_19(e,x,c,l,u,d,e,R,e,v,e,r,s,e,I,n,d,e,x);
922     static const XMLCh inprocTimeout[] =        UNICODE_LITERAL_13(i,n,p,r,o,c,T,i,m,e,o,u,t);
923     static const XMLCh inboundHeader[] =        UNICODE_LITERAL_13(i,n,b,o,u,n,d,H,e,a,d,e,r);
924     static const XMLCh maintainReverseIndex[] = UNICODE_LITERAL_20(m,a,i,n,t,a,i,n,R,e,v,e,r,s,e,I,n,d,e,x);
925     static const XMLCh outboundHeader[] =       UNICODE_LITERAL_14(o,u,t,b,o,u,n,d,H,e,a,d,e,r);
926     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
927     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);
928
929     if (e && e->hasAttributeNS(nullptr, cacheTimeout)) {
930         m_log.warn("cacheTimeout property is deprecated in favor of cacheAllowance (see documentation)");
931         m_cacheTimeout = XMLHelper::getAttrInt(e, 0, cacheTimeout);
932     }
933     m_cacheAllowance = XMLHelper::getAttrInt(e, 0, cacheAllowance);
934     if (inproc)
935         m_inprocTimeout = XMLHelper::getAttrInt(e, 900, inprocTimeout);
936     m_inboundHeader = XMLHelper::getAttrString(e, nullptr, inboundHeader);
937     if (!m_inboundHeader.empty())
938         RemotedHandler::addRemotedHeader(m_inboundHeader.c_str());
939     m_outboundHeader = XMLHelper::getAttrString(e, nullptr, outboundHeader);
940
941 #ifndef SHIBSP_LITE
942     if (conf.isEnabled(SPConfig::OutOfProcess)) {
943         string ssid(XMLHelper::getAttrString(e, nullptr, _StorageService));
944         if (!ssid.empty()) {
945             m_storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
946             if (m_storage)
947                 m_log.info("bound to StorageService (%s)", ssid.c_str());
948             else
949                 throw ConfigurationException("SessionCache unable to locate StorageService ($1), check configuration.", params(1, ssid.c_str()));
950         }
951         if (!m_storage) {
952             m_storage = conf.getServiceProvider()->getStorageService(nullptr);
953             if (m_storage)
954                 m_log.info("bound to arbitrary StorageService");
955             else
956                 throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
957         }
958
959         ssid = XMLHelper::getAttrString(e, nullptr, _StorageServiceLite);
960         if (!ssid.empty()) {
961             m_storage_lite = conf.getServiceProvider()->getStorageService(ssid.c_str());
962             if (m_storage_lite)
963                 m_log.info("bound to 'lite' StorageService (%s)", ssid.c_str());
964             else
965                 throw ConfigurationException("SessionCache unable to locate 'lite' StorageService ($1), check configuration.", params(1, ssid.c_str()));
966         }
967         if (!m_storage_lite) {
968             m_log.info("StorageService for 'lite' use not set, using standard StorageService");
969             m_storage_lite = m_storage;
970         }
971
972         m_cacheAssertions = XMLHelper::getAttrBool(e, true, cacheAssertions);
973         m_reverseIndex = XMLHelper::getAttrBool(e, true, maintainReverseIndex);
974         const XMLCh* excludedNames = e ? e->getAttributeNS(nullptr, excludeReverseIndex) : nullptr;
975         if (excludedNames && *excludedNames) {
976             XMLStringTokenizer toks(excludedNames);
977             while (toks.hasMoreTokens())
978                 m_excludedNames.insert(toks.nextToken());
979         }
980     }
981 #endif
982
983     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
984     if (inproc) {
985         if (!conf.isEnabled(SPConfig::OutOfProcess) && !listener)
986             throw ConfigurationException("SessionCache requires a ListenerService, but none available.");
987         m_lock.reset(RWLock::create());
988         shutdown_wait.reset(CondWait::create());
989         cleanup_thread.reset(Thread::create(&cleanup_fn, this));
990     }
991 #ifndef SHIBSP_LITE
992     else {
993         if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
994             listener->regListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
995             listener->regListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
996             listener->regListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
997         }
998         else {
999             m_log.info("no ListenerService available, cache remoting disabled");
1000         }
1001     }
1002 #endif
1003 }
1004
1005 SSCache::~SSCache()
1006 {
1007     if (inproc) {
1008         // Shut down the cleanup thread and let it know...
1009         shutdown = true;
1010         if (shutdown_wait.get())
1011             shutdown_wait->signal();
1012         if (cleanup_thread.get())
1013             cleanup_thread->join(nullptr);
1014
1015         for_each(m_hashtable.begin(),m_hashtable.end(),cleanup_pair<string,StoredSession>());
1016     }
1017 #ifndef SHIBSP_LITE
1018     else {
1019         SPConfig& conf = SPConfig::getConfig();
1020         ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
1021         if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
1022             listener->unregListener("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
1023             listener->unregListener("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
1024             listener->unregListener("touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache",this);
1025         }
1026     }
1027 #endif
1028 }
1029
1030 #ifndef SHIBSP_LITE
1031
1032 void SSCache::test()
1033 {
1034     XMLCh* wide = SAMLConfig::getConfig().generateIdentifier();
1035     auto_ptr_char temp(wide);
1036     XMLString::release(&wide);
1037     m_storage->createString("SessionCacheTest", temp.get(), "Test", time(nullptr) + 60);
1038     m_storage->deleteString("SessionCacheTest", temp.get());
1039 }
1040
1041 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index, short attempts)
1042 {
1043     if (attempts > 10) {
1044         throw IOException("Exceeded retry limit.");
1045     }
1046
1047     if (!name || !*name) {
1048         m_log.warn("NameID value was empty or null, ignoring request to store for logout");
1049         return;
1050     }
1051
1052     string dup;
1053     unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1054     if (strlen(name) > storageLimit) {
1055         dup = string(name).substr(0, storageLimit);
1056         name = dup.c_str();
1057     }
1058
1059     DDF obj;
1060     DDFJanitor jobj(obj);
1061
1062     // Since we can't guarantee uniqueness, check for an existing record.
1063     string record;
1064     time_t recordexp;
1065     int ver = m_storage_lite->readText("NameID", name, &record, &recordexp);
1066     if (ver > 0) {
1067         // Existing record, so we need to unmarshall it.
1068         istringstream in(record);
1069         in >> obj;
1070     }
1071     else {
1072         // New record.
1073         obj = DDF(nullptr).structure();
1074     }
1075
1076     if (!index || !*index)
1077         index = "_shibnull";
1078     DDF sessions = obj.addmember(index);
1079     if (!sessions.islist())
1080         sessions.list();
1081     DDF session = DDF(nullptr).string(key);
1082     sessions.add(session);
1083
1084     // Remarshall the record.
1085     ostringstream out;
1086     out << obj;
1087
1088     // Try and store it back...
1089     if (ver > 0) {
1090         ver = m_storage_lite->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
1091         if (ver <= 0) {
1092             // Out of sync, or went missing, so retry.
1093             return insert(key, expires, name, index, attempts + 1);
1094         }
1095     }
1096     else if (!m_storage_lite->createText("NameID", name, out.str().c_str(), expires)) {
1097         // Hit a dup, so just retry, hopefully hitting the other branch.
1098         return insert(key, expires, name, index, attempts + 1);
1099     }
1100 }
1101
1102 void SSCache::insert(
1103     string& sessionID,
1104     const Application& app,
1105     const HTTPRequest& httpRequest,
1106     HTTPResponse& httpResponse,
1107     time_t expires,
1108     const saml2md::EntityDescriptor* issuer,
1109     const XMLCh* protocol,
1110     const saml2::NameID* nameid,
1111     const XMLCh* authn_instant,
1112     const XMLCh* session_index,
1113     const XMLCh* authncontext_class,
1114     const XMLCh* authncontext_decl,
1115     const vector<const Assertion*>* tokens,
1116     const vector<Attribute*>* attributes
1117     )
1118 {
1119 #ifdef _DEBUG
1120     xmltooling::NDC ndc("insert");
1121 #endif
1122     if (!m_storage)
1123         throw ConfigurationException("SessionCache insertion requires a StorageService.");
1124
1125     m_log.debug("creating new session");
1126
1127     time_t now = time(nullptr);
1128     auto_ptr_char index(session_index);
1129     auto_ptr_char entity_id(issuer ? issuer->getEntityID() : nullptr);
1130     auto_ptr_char name(nameid ? nameid->getName() : nullptr);
1131
1132     if (name.get() && *name.get()) {
1133         // Check for a pending logout.
1134         unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1135         string namebuf = name.get();
1136         if (namebuf.length() > storageLimit)
1137             namebuf = namebuf.substr(0, storageLimit);
1138         string pending;
1139         int ver = m_storage_lite->readText("Logout", namebuf.c_str(), &pending);
1140         if (ver > 0) {
1141             DDF pendobj;
1142             DDFJanitor jpend(pendobj);
1143             istringstream pstr(pending);
1144             pstr >> pendobj;
1145             // IdP.SP.index contains logout expiration, if any.
1146             DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][app.getRelyingParty(issuer)->getString("entityID").second];
1147             const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
1148             if (!logexpstr && session_index)    // we tried an exact session match, now try for nullptr
1149                 logexpstr = deadmenwalking["_shibnull"].string();
1150             if (logexpstr) {
1151                 auto_ptr_XMLCh dt(logexpstr);
1152                 DateTime dtobj(dt.get());
1153                 dtobj.parseDateTime();
1154                 time_t logexp = dtobj.getEpoch();
1155                 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
1156                     throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
1157             }
1158         }
1159     }
1160
1161     XMLCh* widekey = SAMLConfig::getConfig().generateIdentifier();
1162     auto_ptr_char key(widekey);
1163     XMLString::release(&widekey);
1164
1165     // Store session properties in DDF.
1166     DDF obj = DDF(key.get()).structure();
1167     DDFJanitor entryobj(obj);
1168     obj.addmember("version").integer(1);
1169     obj.addmember("application_id").string(app.getId());
1170
1171     // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1172 #ifndef HAVE_GMTIME_R
1173     struct tm* ptime=gmtime(&expires);
1174 #else
1175     struct tm res;
1176     struct tm* ptime=gmtime_r(&expires,&res);
1177 #endif
1178     char timebuf[32];
1179     strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1180     obj.addmember("expires").string(timebuf);
1181
1182     string caddr(httpRequest.getRemoteAddr());
1183     if (!caddr.empty()) {
1184         DDF addrobj = obj.addmember("client_addr").structure();
1185         addrobj.addmember(getAddressFamily(caddr.c_str())).string(caddr.c_str());
1186     }
1187
1188     if (issuer)
1189         obj.addmember("entity_id").string(entity_id.get());
1190     if (protocol) {
1191         auto_ptr_char prot(protocol);
1192         obj.addmember("protocol").string(prot.get());
1193     }
1194     if (authn_instant) {
1195         auto_ptr_char instant(authn_instant);
1196         obj.addmember("authn_instant").string(instant.get());
1197     }
1198     if (session_index)
1199         obj.addmember("session_index").string(index.get());
1200     if (authncontext_class) {
1201         auto_ptr_char ac(authncontext_class);
1202         obj.addmember("authncontext_class").string(ac.get());
1203     }
1204     if (authncontext_decl) {
1205         auto_ptr_char ad(authncontext_decl);
1206         obj.addmember("authncontext_decl").string(ad.get());
1207     }
1208
1209     if (nameid) {
1210         ostringstream namestr;
1211         namestr << *nameid;
1212         obj.addmember("nameid").string(namestr.str().c_str());
1213     }
1214
1215     if (tokens && m_cacheAssertions) {
1216         obj.addmember("assertions").list();
1217         for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1218             auto_ptr_char tokenid((*t)->getID());
1219             DDF tokid = DDF(nullptr).string(tokenid.get());
1220             obj["assertions"].add(tokid);
1221         }
1222     }
1223
1224     if (attributes) {
1225         DDF attr;
1226         DDF attrlist = obj.addmember("attributes").list();
1227         for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
1228             attr = (*a)->marshall();
1229             attrlist.add(attr);
1230         }
1231     }
1232
1233     ostringstream record;
1234     record << obj;
1235
1236     m_log.debug("storing new session...");
1237     unsigned long cacheTimeout = getCacheTimeout(app);
1238     if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + cacheTimeout))
1239         throw FatalProfileException("Attempted to create a session with a duplicate key.");
1240
1241     // Store the reverse mapping for logout.
1242     if (name.get() && *name.get() && m_reverseIndex
1243             && (m_excludedNames.size() == 0 || m_excludedNames.count(nameid->getName()) == 0)) {
1244         try {
1245             insert(key.get(), expires, name.get(), index.get());
1246         }
1247         catch (std::exception& ex) {
1248             m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
1249         }
1250     }
1251
1252     if (tokens && m_cacheAssertions) {
1253         try {
1254             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
1255                 ostringstream tokenstr;
1256                 tokenstr << *(*t);
1257                 auto_ptr_char tokenid((*t)->getID());
1258                 if (!tokenid.get() || !*tokenid.get() || strlen(tokenid.get()) > m_storage->getCapabilities().getKeySize())
1259                     throw IOException("Assertion ID is missing or exceeds key size of storage service.");
1260                 else if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + cacheTimeout))
1261                     throw IOException("Duplicate assertion ID ($1)", params(1, tokenid.get()));
1262             }
1263         }
1264         catch (std::exception& ex) {
1265             m_log.error("error storing assertion along with session: %s", ex.what());
1266         }
1267     }
1268
1269     const char* pid = obj["entity_id"].string();
1270     const char* prot = obj["protocol"].string();
1271     m_log.info("new session created: ID (%s) IdP (%s) Protocol(%s) Address (%s)",
1272         key.get(), pid ? pid : "none", prot ? prot : "none", httpRequest.getRemoteAddr().c_str());
1273
1274     if (!m_outboundHeader.empty())
1275         httpResponse.setResponseHeader(m_outboundHeader.c_str(), key.get());
1276
1277     time_t cookieLifetime = 0;
1278     pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_", &cookieLifetime);
1279     string k(key.get());
1280     k += shib_cookie.second;
1281
1282     if (cookieLifetime > 0) {
1283         cookieLifetime += now;
1284 #ifndef HAVE_GMTIME_R
1285         ptime=gmtime(&cookieLifetime);
1286 #else
1287         ptime=gmtime_r(&cookieLifetime,&res);
1288 #endif
1289         char cookietimebuf[64];
1290         strftime(cookietimebuf,64,"; expires=%a, %d %b %Y %H:%M:%S GMT",ptime);
1291         k += cookietimebuf;
1292     }
1293
1294     httpResponse.setCookie(shib_cookie.first.c_str(), k.c_str());
1295     sessionID = key.get();
1296 }
1297
1298 bool SSCache::matches(
1299     const Application& app,
1300     const xmltooling::HTTPRequest& request,
1301     const saml2md::EntityDescriptor* issuer,
1302     const saml2::NameID& nameid,
1303     const set<string>* indexes
1304     )
1305 {
1306     auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1307     try {
1308         Session* session = find(app, request);
1309         if (session) {
1310             Locker locker(session, false);
1311             if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
1312                     stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1313                 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
1314             }
1315         }
1316     }
1317     catch (std::exception& ex) {
1318         m_log.error("error while matching session: %s", ex.what());
1319     }
1320     return false;
1321 }
1322
1323 vector<string>::size_type SSCache::_logout(
1324     const Application& app,
1325     const saml2md::EntityDescriptor* issuer,
1326     const saml2::NameID& nameid,
1327     const set<string>* indexes,
1328     time_t expires,
1329     vector<string>& sessionsKilled,
1330     short attempts
1331     )
1332 {
1333 #ifdef _DEBUG
1334     xmltooling::NDC ndc("logout");
1335 #endif
1336
1337     if (!m_storage)
1338         throw ConfigurationException("SessionCache logout requires a StorageService.");
1339     else if (attempts > 10)
1340         throw IOException("Exceeded retry limit.");
1341
1342     auto_ptr_char entityID(issuer ? issuer->getEntityID() : nullptr);
1343     auto_ptr_char name(nameid.getName());
1344
1345     m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
1346
1347     unsigned int storageLimit = m_storage_lite->getCapabilities().getKeySize();
1348     if (strlen(name.get()) > storageLimit)
1349         const_cast<char*>(name.get())[storageLimit] = 0;
1350
1351     DDF obj;
1352     DDFJanitor jobj(obj);
1353     string record;
1354     int ver;
1355
1356     if (expires) {
1357         // Record the logout to prevent post-delivered assertions.
1358         // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1359 #ifndef HAVE_GMTIME_R
1360         struct tm* ptime=gmtime(&expires);
1361 #else
1362         struct tm res;
1363         struct tm* ptime=gmtime_r(&expires,&res);
1364 #endif
1365         char timebuf[32];
1366         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1367
1368         time_t oldexp = 0;
1369         ver = m_storage_lite->readText("Logout", name.get(), &record, &oldexp);
1370         if (ver > 0) {
1371             istringstream lin(record);
1372             lin >> obj;
1373         }
1374         else {
1375             obj = DDF(nullptr).structure();
1376         }
1377
1378         // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
1379         DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(app.getRelyingParty(issuer)->getString("entityID").second);
1380         if (indexes) {
1381             for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
1382                 root.addmember(x->c_str()).string(timebuf);
1383         }
1384         else {
1385             root.addmember("_shibnull").string(timebuf);
1386         }
1387
1388         // Write it back.
1389         ostringstream lout;
1390         lout << obj;
1391
1392         if (ver > 0) {
1393             ver = m_storage_lite->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
1394             if (ver <= 0) {
1395                 // Out of sync, or went missing, so retry.
1396                 return _logout(app, issuer, nameid, indexes, expires, sessionsKilled, attempts + 1);
1397             }
1398         }
1399         else if (!m_storage_lite->createText("Logout", name.get(), lout.str().c_str(), expires)) {
1400             // Hit a dup, so just retry, hopefully hitting the other branch.
1401             return _logout(app, issuer, nameid, indexes, expires, sessionsKilled, attempts + 1);
1402         }
1403
1404         obj.destroy();
1405         record.erase();
1406     }
1407
1408     if (!m_reverseIndex) {
1409         m_log.error("cannot support logout because maintainReverseIndex property is turned off");
1410         throw ConfigurationException("Logout is unsupported by the session cache configuration.");
1411     }
1412
1413     // Read in potentially matching sessions.
1414     ver = m_storage_lite->readText("NameID", name.get(), &record);
1415     if (ver == 0) {
1416         m_log.debug("no active sessions to logout for supplied issuer and subject");
1417         return 0;
1418     }
1419
1420     istringstream in(record);
1421     in >> obj;
1422
1423     // The record contains child lists for each known session index.
1424     DDF key;
1425     DDF sessions = obj.first();
1426     while (sessions.islist()) {
1427         if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
1428             key = sessions.first();
1429             while (key.isstring()) {
1430                 // Fetch the session for comparison.
1431                 Session* session = nullptr;
1432                 try {
1433                     session = find(app, key.string());
1434                 }
1435                 catch (std::exception& ex) {
1436                     m_log.error("error locating session (%s): %s", key.string(), ex.what());
1437                 }
1438
1439                 if (session) {
1440                     Locker locker(session, false);
1441                     // Same issuer?
1442                     if (XMLString::equals(session->getEntityID(), entityID.get())) {
1443                         // Same NameID?
1444                         if (stronglyMatches(issuer->getEntityID(), app.getRelyingParty(issuer)->getXMLString("entityID").second, nameid, *session->getNameID())) {
1445                             sessionsKilled.push_back(key.string());
1446                             key.destroy();
1447                         }
1448                         else {
1449                             m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
1450                         }
1451                     }
1452                     else {
1453                         m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
1454                     }
1455                 }
1456                 else {
1457                     // Session may already be gone, or it may be associated with a different application.
1458                     // To be conservative, we'll leave it alone. This isn't really increasing our security
1459                     // risk, because if we can't lookup the session, it's unlikely the calling logout code
1460                     // can either, so there's no chance of removing the session anyway.
1461                     m_log.warn("session (%s) not accessible for logout, may be gone, or associated with a different application", key.string());
1462                 }
1463                 key = sessions.next();
1464             }
1465
1466             // No sessions left for this index?
1467             if (sessions.first().isnull())
1468                 sessions.destroy();
1469         }
1470         sessions = obj.next();
1471     }
1472
1473     if (obj.first().isnull())
1474         obj.destroy();
1475
1476     // If possible, write back the mapping record (this isn't crucial).
1477     try {
1478         if (obj.isnull()) {
1479             m_storage_lite->deleteText("NameID", name.get());
1480         }
1481         else if (!sessionsKilled.empty()) {
1482             ostringstream out;
1483             out << obj;
1484             if (m_storage_lite->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1485                 m_log.warn("logout mapping record changed behind us, leaving it alone");
1486         }
1487     }
1488     catch (std::exception& ex) {
1489         m_log.error("error updating logout mapping record: %s", ex.what());
1490     }
1491
1492     return sessionsKilled.size();
1493 }
1494
1495 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1496 {
1497     if (!XMLString::equals(n1.getName(), n2.getName()))
1498         return false;
1499
1500     const XMLCh* s1 = n1.getFormat();
1501     const XMLCh* s2 = n2.getFormat();
1502     if (!s1 || !*s1)
1503         s1 = saml2::NameID::UNSPECIFIED;
1504     if (!s2 || !*s2)
1505         s2 = saml2::NameID::UNSPECIFIED;
1506     if (!XMLString::equals(s1,s2))
1507         return false;
1508
1509     s1 = n1.getNameQualifier();
1510     s2 = n2.getNameQualifier();
1511     if (!s1 || !*s1)
1512         s1 = idp;
1513     if (!s2 || !*s2)
1514         s2 = idp;
1515     if (!XMLString::equals(s1,s2))
1516         return false;
1517
1518     s1 = n1.getSPNameQualifier();
1519     s2 = n2.getSPNameQualifier();
1520     if (!s1 || !*s1)
1521         s1 = sp;
1522     if (!s2 || !*s2)
1523         s2 = sp;
1524     if (!XMLString::equals(s1,s2))
1525         return false;
1526
1527     return true;
1528 }
1529
1530 LogoutEvent* SSCache::newLogoutEvent(const Application& app) const
1531 {
1532     if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
1533         return nullptr;
1534     try {
1535         auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGOUT_EVENT, nullptr));
1536         LogoutEvent* logout_event = dynamic_cast<LogoutEvent*>(event.get());
1537         if (logout_event) {
1538             logout_event->m_app = &app;
1539             event.release();
1540             return logout_event;
1541         }
1542         else {
1543             m_log.warn("unable to audit event, log event object was of an incorrect type");
1544         }
1545     }
1546     catch (std::exception& ex) {
1547         m_log.warn("exception auditing event: %s", ex.what());
1548     }
1549     return nullptr;
1550 }
1551
1552 #endif
1553
1554 Session* SSCache::find(const Application& app, const char* key, const char* client_addr, time_t* timeout)
1555 {
1556 #ifdef _DEBUG
1557     xmltooling::NDC ndc("find");
1558 #endif
1559     StoredSession* session=nullptr;
1560
1561     if (inproc) {
1562         m_log.debug("searching local cache for session (%s)", key);
1563         m_lock->rdlock();
1564         map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1565         if (i!=m_hashtable.end()) {
1566             // Save off and lock the session.
1567             session = i->second;
1568             session->lock();
1569             m_lock->unlock();
1570             m_log.debug("session found locally, validating it for use");
1571         }
1572         else {
1573             m_lock->unlock();
1574         }
1575     }
1576
1577     if (!session) {
1578         if (!SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1579             m_log.debug("session not found locally, remoting the search");
1580             // Remote the request.
1581             DDF in("find::"STORAGESERVICE_SESSION_CACHE"::SessionCache"), out;
1582             DDFJanitor jin(in);
1583             in.structure();
1584             in.addmember("key").string(key);
1585             in.addmember("application_id").string(app.getId());
1586             if (timeout && *timeout) {
1587                 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
1588 #ifndef HAVE_GMTIME_R
1589                 struct tm* ptime=gmtime(timeout);
1590 #else
1591                 struct tm res;
1592                 struct tm* ptime=gmtime_r(timeout,&res);
1593 #endif
1594                 char timebuf[32];
1595                 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
1596                 in.addmember("timeout").string(timebuf);
1597             }
1598
1599             try {
1600                 out=app.getServiceProvider().getListenerService()->send(in);
1601                 if (!out.isstruct()) {
1602                     out.destroy();
1603                     m_log.debug("session not found in remote cache");
1604                     return nullptr;
1605                 }
1606
1607                 // Wrap the results in a local entry and save it.
1608                 session = new StoredSession(this, out);
1609                 // The remote end has handled timeout issues, we handle address and expiration checks.
1610                 timeout = nullptr;
1611             }
1612             catch (...) {
1613                 out.destroy();
1614                 throw;
1615             }
1616         }
1617         else {
1618             // We're out of process, so we can search the storage service directly.
1619 #ifndef SHIBSP_LITE
1620             if (!m_storage)
1621                 throw ConfigurationException("SessionCache lookup requires a StorageService.");
1622
1623             m_log.debug("searching for session (%s)", key);
1624
1625             DDF obj;
1626             time_t lastAccess;
1627             string record;
1628             int ver = m_storage->readText(key, "session", &record, &lastAccess);
1629             if (!ver)
1630                 return nullptr;
1631
1632             m_log.debug("reconstituting session and checking validity");
1633
1634             istringstream in(record);
1635             in >> obj;
1636
1637             unsigned long cacheTimeout = getCacheTimeout(app);
1638             lastAccess -= cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched
1639             time_t now=time(nullptr);
1640
1641             if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
1642                 m_log.info("session timed out (ID: %s)", key);
1643                 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1644                 if (logout_event.get()) {
1645                     logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1646                     logout_event->m_sessions.push_back(key);
1647                     app.getServiceProvider().getTransactionLog()->write(*logout_event);
1648                 }
1649                 remove(app, key);
1650                 const char* eid = obj["entity_id"].string();
1651                 if (!eid) {
1652                     obj.destroy();
1653                     throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1654                 }
1655                 string eid2(eid);
1656                 obj.destroy();
1657                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.", namedparams(1, "entityID", eid2.c_str()));
1658             }
1659
1660             if (timeout) {
1661                 // Update storage expiration, if possible.
1662                 try {
1663                     m_storage->updateContext(key, now + cacheTimeout);
1664                 }
1665                 catch (std::exception& ex) {
1666                     m_log.error("failed to update session expiration: %s", ex.what());
1667                 }
1668             }
1669
1670             // Wrap the results in a local entry and save it.
1671             session = new StoredSession(this, obj);
1672             // We handled timeout issues, still need to handle address and expiration checks.
1673             timeout = nullptr;
1674 #else
1675             throw ConfigurationException("SessionCache search requires a StorageService.");
1676 #endif
1677         }
1678
1679         if (inproc) {
1680             // Lock for writing and repeat the search to avoid duplication.
1681             m_lock->wrlock();
1682             SharedLock shared(m_lock, false);
1683             if (m_hashtable.count(key)) {
1684                 // We're using an existing session entry.
1685                 delete session;
1686                 session = m_hashtable[key];
1687                 session->lock();
1688             }
1689             else {
1690                 m_hashtable[key]=session;
1691                 session->lock();
1692             }
1693         }
1694     }
1695
1696     if (!XMLString::equals(session->getApplicationID(), app.getId())) {
1697         m_log.warn("an application (%s) tried to access another application's session", app.getId());
1698         session->unlock();
1699         return nullptr;
1700     }
1701
1702     // Verify currency and update the timestamp if indicated by caller.
1703     try {
1704         session->validate(app, client_addr, timeout);
1705     }
1706     catch (...) {
1707 #ifndef SHIBSP_LITE
1708         scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(app));
1709         if (logout_event.get()) {
1710             logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1711             logout_event->m_session = session;
1712             logout_event->m_sessions.push_back(session->getID());
1713             app.getServiceProvider().getTransactionLog()->write(*logout_event);
1714         }
1715 #endif
1716         session->unlock();
1717         remove(app, key);
1718         throw;
1719     }
1720
1721     return session;
1722 }
1723
1724 Session* SSCache::find(const Application& app, HTTPRequest& request, const char* client_addr, time_t* timeout)
1725 {
1726     string id = active(app, request);
1727     if (id.empty())
1728         return nullptr;
1729     try {
1730         Session* session = find(app, id.c_str(), client_addr, timeout);
1731         if (session)
1732             return session;
1733         HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1734         if (response) {
1735             if (!m_outboundHeader.empty())
1736                 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1737             pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1738             string exp(shib_cookie.second);
1739             exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1740             response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1741         }
1742     }
1743     catch (std::exception&) {
1744         HTTPResponse* response = dynamic_cast<HTTPResponse*>(&request);
1745         if (response) {
1746             if (!m_outboundHeader.empty())
1747                 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1748             pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1749             string exp(shib_cookie.second);
1750             exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1751             response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1752         }
1753         throw;
1754     }
1755     return nullptr;
1756 }
1757
1758 void SSCache::remove(const Application& app, const HTTPRequest& request, HTTPResponse* response)
1759 {
1760     string session_id;
1761     pair<string,const char*> shib_cookie = app.getCookieNameProps("_shibsession_");
1762
1763     if (!m_inboundHeader.empty())
1764         session_id = request.getHeader(m_inboundHeader.c_str());
1765     if (session_id.empty()) {
1766         const char* c = request.getCookie(shib_cookie.first.c_str());
1767         if (c && *c)
1768             session_id = c;
1769     }
1770
1771     if (!session_id.empty()) {
1772         if (response) {
1773             if (!m_outboundHeader.empty())
1774                 response->setResponseHeader(m_outboundHeader.c_str(), nullptr);
1775             string exp(shib_cookie.second);
1776             exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
1777             response->setCookie(shib_cookie.first.c_str(), exp.c_str());
1778         }
1779         remove(app, session_id.c_str());
1780     }
1781 }
1782
1783 void SSCache::remove(const Application& app, const char* key)
1784 {
1785 #ifdef _DEBUG
1786     xmltooling::NDC ndc("remove");
1787 #endif
1788     // Take care of local copy.
1789     if (inproc)
1790         dormant(key);
1791
1792     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1793         // Remove the session from storage directly.
1794 #ifndef SHIBSP_LITE
1795         m_storage->deleteContext(key);
1796         m_log.info("removed session (%s)", key);
1797 #else
1798         throw ConfigurationException("SessionCache removal requires a StorageService.");
1799 #endif
1800     }
1801     else {
1802         // Remote the request.
1803         DDF in("remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache");
1804         DDFJanitor jin(in);
1805         in.structure();
1806         in.addmember("key").string(key);
1807         in.addmember("application_id").string(app.getId());
1808
1809         DDF out = app.getServiceProvider().getListenerService()->send(in);
1810         out.destroy();
1811     }
1812 }
1813
1814 void SSCache::dormant(const char* key)
1815 {
1816 #ifdef _DEBUG
1817     xmltooling::NDC ndc("dormant");
1818 #endif
1819
1820     m_log.debug("deleting local copy of session (%s)", key);
1821
1822     // lock the cache for writing, which means we know nobody is sitting in find()
1823     m_lock->wrlock();
1824
1825     // grab the entry from the table
1826     map<string,StoredSession*>::const_iterator i=m_hashtable.find(key);
1827     if (i==m_hashtable.end()) {
1828         m_lock->unlock();
1829         return;
1830     }
1831
1832     // ok, remove the entry and lock it
1833     StoredSession* entry=i->second;
1834     m_hashtable.erase(key);
1835     entry->lock();
1836
1837     // unlock the cache
1838     m_lock->unlock();
1839
1840     // we can release the cache entry lock because we know we're not in the cache anymore
1841     entry->unlock();
1842
1843     delete entry;
1844 }
1845
1846 void* SSCache::cleanup_fn(void* p)
1847 {
1848 #ifdef _DEBUG
1849     xmltooling::NDC ndc("cleanup");
1850 #endif
1851
1852     SSCache* pcache = reinterpret_cast<SSCache*>(p);
1853
1854 #ifndef WIN32
1855     // First, let's block all signals
1856     Thread::mask_all_signals();
1857 #endif
1858
1859     scoped_ptr<Mutex> mutex(Mutex::create());
1860
1861     // Load our configuration details...
1862     static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
1863     const XMLCh* tag=pcache->m_root ? pcache->m_root->getAttributeNS(nullptr, cleanupInterval) : nullptr;
1864     int rerun_timer = 900;
1865     if (tag && *tag) {
1866         rerun_timer = XMLString::parseInt(tag);
1867         if (rerun_timer <= 0)
1868             rerun_timer = 900;
1869     }
1870
1871     mutex->lock();
1872
1873     pcache->m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, pcache->m_inprocTimeout);
1874
1875     while (!pcache->shutdown) {
1876         pcache->shutdown_wait->timedwait(mutex.get(), rerun_timer);
1877         if (pcache->shutdown)
1878             break;
1879
1880         // Ok, let's run through the cleanup process and clean out
1881         // really old sessions.  This is a two-pass process.  The
1882         // first pass is done holding a read-lock while we iterate over
1883         // the cache.  The second pass doesn't need a lock because
1884         // the 'deletes' will lock the cache.
1885
1886         // Pass 1: iterate over the map and find all entries that have not been
1887         // used in the allotted timeout.
1888         vector<string> stale_keys;
1889         time_t stale = time(nullptr) - pcache->m_inprocTimeout;
1890
1891         pcache->m_log.debug("cleanup thread running");
1892
1893         pcache->m_lock->rdlock();
1894         for (map<string,StoredSession*>::const_iterator i = pcache->m_hashtable.begin(); i != pcache->m_hashtable.end(); ++i) {
1895             // If the last access was BEFORE the stale timeout...
1896             i->second->lock();
1897             time_t last=i->second->getLastAccess();
1898             i->second->unlock();
1899             if (last < stale)
1900                 stale_keys.push_back(i->first);
1901         }
1902         pcache->m_lock->unlock();
1903
1904         if (!stale_keys.empty()) {
1905             pcache->m_log.info("purging %d old sessions", stale_keys.size());
1906
1907             // Pass 2: walk through the list of stale entries and remove them from the cache
1908             for_each(stale_keys.begin(), stale_keys.end(), boost::bind(&SSCache::dormant, pcache, boost::bind(&string::c_str, _1)));
1909         }
1910
1911         pcache->m_log.debug("cleanup thread completed");
1912     }
1913
1914     pcache->m_log.info("cleanup thread exiting");
1915
1916     mutex->unlock();
1917     return nullptr;
1918 }
1919
1920 #ifndef SHIBSP_LITE
1921
1922 void SSCache::receive(DDF& in, ostream& out)
1923 {
1924 #ifdef _DEBUG
1925     xmltooling::NDC ndc("receive");
1926 #endif
1927     const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1928     if (!app)
1929         throw ListenerException("Application not found, check configuration?");
1930
1931     if (!strcmp(in.name(),"find::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1932         const char* key=in["key"].string();
1933         if (!key)
1934             throw ListenerException("Required parameters missing for session lookup.");
1935
1936         // Do an unversioned read.
1937         string record;
1938         time_t lastAccess;
1939         if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1940             m_log.debug("session not found in cache (%s)", key);
1941             DDF ret(nullptr);
1942             DDFJanitor jan(ret);
1943             out << ret;
1944             return;
1945         }
1946
1947         // Adjust for expiration to recover last access time and check timeout.
1948         unsigned long cacheTimeout = getCacheTimeout(*app);
1949         lastAccess -= cacheTimeout;
1950         time_t now=time(nullptr);
1951
1952         // See if we need to check for a timeout.
1953         if (in["timeout"].string()) {
1954             time_t timeout = 0;
1955             auto_ptr_XMLCh dt(in["timeout"].string());
1956             DateTime dtobj(dt.get());
1957             dtobj.parseDateTime();
1958             timeout = dtobj.getEpoch();
1959
1960             if (timeout > 0 && now - lastAccess >= timeout) {
1961                 m_log.info("session timed out (ID: %s)", key);
1962                 scoped_ptr<LogoutEvent> logout_event(newLogoutEvent(*app));
1963                 if (logout_event.get()) {
1964                     logout_event->m_logoutType = LogoutEvent::LOGOUT_EVENT_INVALID;
1965                     logout_event->m_sessions.push_back(key);
1966                     app->getServiceProvider().getTransactionLog()->write(*logout_event);
1967                 }
1968                 remove(*app, key);
1969                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1970             }
1971
1972             // Update storage expiration, if possible.
1973             try {
1974                 m_storage->updateContext(key, now + cacheTimeout);
1975             }
1976             catch (std::exception& ex) {
1977                 m_log.error("failed to update session expiration: %s", ex.what());
1978             }
1979         }
1980
1981         // Send the record back.
1982         out << record;
1983     }
1984     else if (!strcmp(in.name(),"touch::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
1985         const char* key=in["key"].string();
1986         if (!key)
1987             throw ListenerException("Required parameters missing for session check.");
1988         const char* client_addr = in["client_addr"].string();
1989
1990         // Do a read. May be unversioned if we need to bind a new client address.
1991         string record;
1992         time_t lastAccess;
1993         int curver = in["version"].integer();
1994         int ver = m_storage->readText(key, "session", &record, &lastAccess, client_addr ? 0 : curver);
1995         if (ver == 0) {
1996             m_log.warn("unsuccessful read of session (ID: %s), caches out of sync?", key);
1997             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1998         }
1999
2000         // Adjust for expiration to recover last access time and check timeout.
2001         unsigned long cacheTimeout = getCacheTimeout(*app);
2002         lastAccess -= cacheTimeout;
2003         time_t now=time(nullptr);
2004
2005         // See if we need to check for a timeout.
2006         time_t timeout = 0;
2007         auto_ptr_XMLCh dt(in["timeout"].string());
2008         if (dt.get()) {
2009             DateTime dtobj(dt.get());
2010             dtobj.parseDateTime();
2011             timeout = dtobj.getEpoch();
2012         }
2013
2014         if (timeout > 0 && now - lastAccess >= timeout) {
2015             m_log.info("session timed out (ID: %s)", key);
2016             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
2017         }
2018
2019         // Update storage expiration, if possible.
2020         try {
2021             m_storage->updateContext(key, now + cacheTimeout);
2022         }
2023         catch (std::exception& ex) {
2024             m_log.error("failed to update session expiration: %s", ex.what());
2025         }
2026
2027         // We may need to write back a new address into the session using a versioned update loop.
2028         if (client_addr) {
2029             short attempts = 0;
2030             m_log.info("binding session (%s) to new client address (%s)", key, client_addr);
2031             do {
2032                 // We have to reconstitute the session object ourselves.
2033                 DDF sessionobj;
2034                 DDFJanitor sessionjan(sessionobj);
2035                 istringstream src(record);
2036                 src >> sessionobj;
2037                 ver = sessionobj["version"].integer();
2038                 const char* saddr = sessionobj["client_addr"][getAddressFamily(client_addr)].string();
2039                 if (saddr) {
2040                     // Something snuck in and bound the session to this address type, so it better match what we have.
2041                     if (!XMLString::equals(saddr, client_addr)) {
2042                         m_log.warn("client address mismatch, client (%s), session (%s)", client_addr, saddr);
2043                         throw RetryableProfileException(
2044                             "Your IP address ($1) does not match the address recorded at the time the session was established.",
2045                             params(1, client_addr)
2046                             );
2047                     }
2048                     break;  // No need to update.
2049                 }
2050                 else {
2051                     // Bind it into the session.
2052                     sessionobj["client_addr"].addmember(getAddressFamily(client_addr)).string(client_addr);
2053                 }
2054
2055                 // Tentatively increment the version.
2056                 sessionobj["version"].integer(sessionobj["version"].integer() + 1);
2057
2058                 ostringstream str;
2059                 str << sessionobj;
2060                 record = str.str();
2061
2062                 ver = m_storage->updateText(key, "session", record.c_str(), 0, ver);
2063                 if (!ver) {
2064                     // Fatal problem with update.
2065                     m_log.error("updateText failed on StorageService for session (%s)", key);
2066                     throw IOException("Unable to update stored session.");
2067                 }
2068                 if (ver < 0) {
2069                     // Out of sync.
2070                     if (++attempts > 10) {
2071                         m_log.error("failed to bind client address, update attempts exceeded limit");
2072                         throw IOException("Unable to update stored session, exceeded retry limit.");
2073                     }
2074                     m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
2075                     sessionobj["version"].integer(sessionobj["version"].integer() - 1);
2076                     ver = m_storage->readText(key, "session", &record);
2077                     if (!ver) {
2078                         m_log.error("readText failed on StorageService for session (%s)", key);
2079                         throw IOException("Unable to read back stored session.");
2080                     }
2081                     ver = -1;
2082                 }
2083             } while (ver < 0); // negative indicates a sync issue so we retry
2084         }
2085
2086         if (ver > curver) {
2087             // Send the record back.
2088             out << record;
2089         }
2090         else {
2091             DDF ret(nullptr);
2092             DDFJanitor jan(ret);
2093             out << ret;
2094         }
2095     }
2096     else if (!strcmp(in.name(),"remove::"STORAGESERVICE_SESSION_CACHE"::SessionCache")) {
2097         const char* key=in["key"].string();
2098         if (!key)
2099             throw ListenerException("Required parameter missing for session removal.");
2100
2101         remove(*app, key);
2102         DDF ret(nullptr);
2103         DDFJanitor jan(ret);
2104         out << ret;
2105     }
2106 }
2107
2108 #endif