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