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