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