Revise attribute APIs to use vectors in place of multimaps.
[shibboleth/sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
1 /*
2  *  Copyright 2001-2007 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 "SessionCache.h"
36 #include "TransactionLog.h"
37 #include "attribute/Attribute.h"
38 #include "remoting/ListenerService.h"
39 #include "util/SPConstants.h"
40
41 #include <saml/SAMLConfig.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/StorageService.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
46
47 using namespace shibsp;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmltooling;
51 using namespace std;
52
53 namespace shibsp {
54
55     class SSCache;
56     class StoredSession : public virtual Session
57     {
58     public:
59         StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {
60             const char* nameid = obj["nameid"].string();
61             if (nameid) {
62                 // Parse and bind the document into an XMLObject.
63                 istringstream instr(nameid);
64                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); 
65                 XercesJanitor<DOMDocument> janitor(doc);
66                 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());
67                 n->unmarshall(doc->getDocumentElement(), true);
68                 janitor.release();
69                 m_nameid = n.release();
70             }
71         }
72         
73         ~StoredSession();
74         
75         Lockable* lock() {
76             return this;
77         }
78         void unlock() {
79             delete this;
80         }
81         
82         const char* getID() const {
83             return m_obj.name();
84         }
85         const char* getClientAddress() const {
86             return m_obj["client_addr"].string();
87         }
88         const char* getEntityID() const {
89             return m_obj["entity_id"].string();
90         }
91         const char* getProtocol() const {
92             return m_obj["protocol"].string();
93         }
94         const char* getAuthnInstant() const {
95             return m_obj["authn_instant"].string();
96         }
97         const opensaml::saml2::NameID* getNameID() const {
98             return m_nameid;
99         }
100         const char* getSessionIndex() const {
101             return m_obj["session_index"].string();
102         }
103         const char* getAuthnContextClassRef() const {
104             return m_obj["authncontext_class"].string();
105         }
106         const char* getAuthnContextDeclRef() const {
107             return m_obj["authncontext_decl"].string();
108         }
109         const vector<Attribute*>& getAttributes() const {
110             if (m_attributes.empty())
111                 unmarshallAttributes();
112             return m_attributes;
113         }
114         const multimap<string,const Attribute*>& getIndexedAttributes() const {
115             if (m_attributes.empty())
116                 unmarshallAttributes();
117             return m_attributeIndex;
118         }
119         const vector<const char*>& getAssertionIDs() const {
120             if (m_ids.empty()) {
121                 DDF ids = m_obj["assertions"];
122                 DDF id = ids.first();
123                 while (id.isstring()) {
124                     m_ids.push_back(id.string());
125                     id = ids.next();
126                 }
127             }
128             return m_ids;
129         }
130         
131         void addAttributes(const vector<Attribute*>& attributes);
132         const Assertion* getAssertion(const char* id) const;
133         void addAssertion(Assertion* assertion);
134
135     private:
136         void unmarshallAttributes() const;
137
138         DDF m_obj;
139         saml2::NameID* m_nameid;
140         mutable vector<Attribute*> m_attributes;
141         mutable multimap<string,const Attribute*> m_attributeIndex;
142         mutable vector<const char*> m_ids;
143         mutable map<string,Assertion*> m_tokens;
144         SSCache* m_cache;
145     };
146     
147     class SSCache : public SessionCache, public virtual Remoted
148     {
149     public:
150         SSCache(const DOMElement* e);
151         ~SSCache();
152     
153         void receive(DDF& in, ostream& out);
154         
155         string insert(
156             time_t expires,
157             const Application& application,
158             const char* client_addr=NULL,
159             const saml2md::EntityDescriptor* issuer=NULL,
160             const XMLCh* protocol=NULL,
161             const saml2::NameID* nameid=NULL,
162             const XMLCh* authn_instant=NULL,
163             const XMLCh* session_index=NULL,
164             const XMLCh* authncontext_class=NULL,
165             const XMLCh* authncontext_decl=NULL,
166             const vector<const Assertion*>* tokens=NULL,
167             const vector<Attribute*>* attributes=NULL
168             );
169         Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
170         void remove(const char* key, const Application& application);
171         bool matches(
172             const char* key,
173             const saml2md::EntityDescriptor* issuer,
174             const saml2::NameID& nameid,
175             const set<string>* indexes,
176             const Application& application
177             );
178         vector<string>::size_type logout(
179             const saml2md::EntityDescriptor* issuer,
180             const saml2::NameID& nameid,
181             const set<string>* indexes,
182             time_t expires,
183             const Application& application,
184             vector<string>& sessions
185             );
186
187         Category& m_log;
188         StorageService* m_storage;
189
190     private:
191         // maintain back-mappings of NameID/SessionIndex -> session key
192         void insert(const char* key, time_t expires, const char* name, const char* index);
193
194         bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
195     };
196
197     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)
198     {
199         return new SSCache(e);
200     }
201
202     static const XMLCh _StorageService[] =   UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
203 }
204
205 StoredSession::~StoredSession()
206 {
207     m_obj.destroy();
208     delete m_nameid;
209     for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
210     for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());
211 }
212
213 void StoredSession::unmarshallAttributes() const
214 {
215     Attribute* attribute;
216     DDF attrs = m_obj["attributes"];
217     DDF attr = attrs.first();
218     while (!attr.isnull()) {
219         try {
220             attribute = Attribute::unmarshall(attr);
221             m_attributes.push_back(attribute);
222             m_attributeIndex.insert(make_pair(attribute->getId(), attribute));
223             if (m_cache->m_log.isDebugEnabled())
224                 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
225                     attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
226         }
227         catch (AttributeException& ex) {
228             const char* id = attr.first().name();
229             m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
230         }
231         attr = attrs.next();
232     }
233 }
234
235 void StoredSession::addAttributes(const vector<Attribute*>& attributes)
236 {
237 #ifdef _DEBUG
238     xmltooling::NDC ndc("addAttributes");
239 #endif
240
241     m_cache->m_log.debug("adding attributes to session (%s)", getID());
242     
243     int ver;
244     do {
245         DDF attr;
246         DDF attrs = m_obj["attributes"];
247         if (!attrs.islist())
248             attrs = m_obj.addmember("attributes").list();
249         for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {
250             attr = (*a)->marshall();
251             attrs.add(attr);
252         }
253         
254         // Tentatively increment the version.
255         m_obj["version"].integer(m_obj["version"].integer()+1);
256         
257         ostringstream str;
258         str << m_obj;
259         string record(str.str()); 
260
261         try {
262             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
263         }
264         catch (exception&) {
265             // Roll back modification to record.
266             m_obj["version"].integer(m_obj["version"].integer()-1);
267             vector<Attribute*>::size_type count = attributes.size();
268             while (count--)
269                 attrs.last().destroy();            
270             throw;
271         }
272
273         if (ver <= 0) {
274             // Roll back modification to record.
275             m_obj["version"].integer(m_obj["version"].integer()-1);
276             vector<Attribute*>::size_type count = attributes.size();
277             while (count--)
278                 attrs.last().destroy();            
279         }
280         if (!ver) {
281             // Fatal problem with update.
282             throw IOException("Unable to update stored session.");
283         }
284         else if (ver < 0) {
285             // Out of sync.
286             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
287             ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
288             if (!ver) {
289                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
290                 throw IOException("Unable to read back stored session.");
291             }
292             
293             // Reset object.
294             DDF newobj;
295             istringstream in(record);
296             in >> newobj;
297
298             m_ids.clear();
299             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
300             m_attributes.clear();
301             m_attributeIndex.clear();
302             newobj["version"].integer(ver);
303             m_obj.destroy();
304             m_obj = newobj;
305
306             ver = -1;
307         }
308     } while (ver < 0);  // negative indicates a sync issue so we retry
309
310     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
311     Locker locker(xlog);
312     xlog->log.infoStream() <<
313         "Added the following attributes to session (ID: " <<
314             getID() <<
315         ") for (applicationId: " <<
316             m_obj["application_id"].string() <<
317         ") {";
318     for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)
319         xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
320     xlog->log.info("}");
321
322     // We own them now, so clean them up.
323     for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
324 }
325
326 const Assertion* StoredSession::getAssertion(const char* id) const
327 {
328     map<string,Assertion*>::const_iterator i = m_tokens.find(id);
329     if (i!=m_tokens.end())
330         return i->second;
331     
332     string tokenstr;
333     if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))
334         throw FatalProfileException("Assertion not found in cache.");
335
336     // Parse and bind the document into an XMLObject.
337     istringstream instr(tokenstr);
338     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); 
339     XercesJanitor<DOMDocument> janitor(doc);
340     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
341     janitor.release();
342     
343     Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());
344     if (!token)
345         throw FatalProfileException("Request for cached assertion returned an unknown object type.");
346
347     // Transfer ownership to us.
348     xmlObject.release();
349     m_tokens[id]=token;
350     return token;
351 }
352
353 void StoredSession::addAssertion(Assertion* assertion)
354 {
355 #ifdef _DEBUG
356     xmltooling::NDC ndc("addAssertion");
357 #endif
358     
359     if (!assertion)
360         throw FatalProfileException("Unknown object type passed to session for storage.");
361
362     auto_ptr_char id(assertion->getID());
363
364     m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());
365
366     time_t exp;
367     if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))
368         throw IOException("Unable to load expiration time for stored session.");
369
370     ostringstream tokenstr;
371     tokenstr << *assertion;
372     if (!m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp))
373         throw IOException("Attempted to insert duplicate assertion ID into session.");
374     
375     int ver;
376     do {
377         DDF token = DDF(NULL).string(id.get());
378         m_obj["assertions"].add(token);
379
380         // Tentatively increment the version.
381         m_obj["version"].integer(m_obj["version"].integer()+1);
382     
383         ostringstream str;
384         str << m_obj;
385         string record(str.str()); 
386
387         try {
388             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);
389         }
390         catch (exception&) {
391             token.destroy();
392             m_obj["version"].integer(m_obj["version"].integer()-1);
393             m_cache->m_storage->deleteText(getID(), id.get());
394             throw;
395         }
396
397         if (ver <= 0) {
398             token.destroy();
399             m_obj["version"].integer(m_obj["version"].integer()-1);
400         }            
401         if (!ver) {
402             // Fatal problem with update.
403             m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());
404             m_cache->m_storage->deleteText(getID(), id.get());
405             throw IOException("Unable to update stored session.");
406         }
407         else if (ver < 0) {
408             // Out of sync.
409             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");
410             ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);
411             if (!ver) {
412                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());
413                 m_cache->m_storage->deleteText(getID(), id.get());
414                 throw IOException("Unable to read back stored session.");
415             }
416             
417             // Reset object.
418             DDF newobj;
419             istringstream in(record);
420             in >> newobj;
421
422             m_ids.clear();
423             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
424             m_attributes.clear();
425             m_attributeIndex.clear();
426             newobj["version"].integer(ver);
427             m_obj.destroy();
428             m_obj = newobj;
429             
430             ver = -1;
431         }
432     } while (ver < 0); // negative indicates a sync issue so we retry
433
434     m_ids.clear();
435     delete assertion;
436
437     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();
438     Locker locker(xlog);
439     xlog->log.info(
440         "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",
441         id.get(), m_obj["application_id"].string(), getID()
442         );
443 }
444
445 SSCache::SSCache(const DOMElement* e)
446     : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)
447 {
448     SPConfig& conf = SPConfig::getConfig();
449     const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;
450     if (tag && *tag) {
451         auto_ptr_char ssid(tag);
452         m_storage = conf.getServiceProvider()->getStorageService(ssid.get());
453         if (m_storage)
454             m_log.info("bound to StorageService (%s)", ssid.get());
455         else
456             throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");
457     }
458
459     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
460     if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
461         listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
462         listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
463         listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
464         listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
465     }
466     else {
467         m_log.info("no ListenerService available, cache remoting disabled");
468     }
469 }
470
471 SSCache::~SSCache()
472 {
473     SPConfig& conf = SPConfig::getConfig();
474     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
475     if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {
476         listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);
477         listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);
478         listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);
479         listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);
480     }
481 }
482
483 void SSCache::insert(const char* key, time_t expires, const char* name, const char* index)
484 {
485     string dup;
486     if (strlen(name) > 255) {
487         dup = string(name).substr(0,255);
488         name = dup.c_str();
489     }
490
491     DDF obj;
492     DDFJanitor jobj(obj);
493
494     // Since we can't guarantee uniqueness, check for an existing record.
495     string record;
496     time_t recordexp;
497     int ver = m_storage->readText("NameID", name, &record, &recordexp);
498     if (ver > 0) {
499         // Existing record, so we need to unmarshall it.
500         istringstream in(record);
501         in >> obj;
502     }
503     else {
504         // New record.
505         obj.structure();
506     }
507
508     if (!index || !*index)
509         index = "_shibnull";
510     DDF sessions = obj.addmember(index);
511     if (!sessions.islist())
512         sessions.list();
513     DDF session = DDF(NULL).string(key);
514     sessions.add(session);
515
516     // Remarshall the record.
517     ostringstream out;
518     out << obj;
519
520     // Try and store it back...
521     if (ver > 0) {
522         ver = m_storage->updateText("NameID", name, out.str().c_str(), max(expires, recordexp), ver);
523         if (ver <= 0) {
524             // Out of sync, or went missing, so retry.
525             return insert(key, expires, name, index);
526         }
527     }
528     else if (!m_storage->createText("NameID", name, out.str().c_str(), expires)) {
529         // Hit a dup, so just retry, hopefully hitting the other branch.
530         return insert(key, expires, name, index);
531     }
532 }
533
534 string SSCache::insert(
535     time_t expires,
536     const Application& application,
537     const char* client_addr,
538     const saml2md::EntityDescriptor* issuer,
539     const XMLCh* protocol,
540     const saml2::NameID* nameid,
541     const XMLCh* authn_instant,
542     const XMLCh* session_index,
543     const XMLCh* authncontext_class,
544     const XMLCh* authncontext_decl,
545     const vector<const Assertion*>* tokens,
546     const vector<Attribute*>* attributes
547     )
548 {
549 #ifdef _DEBUG
550     xmltooling::NDC ndc("insert");
551 #endif
552
553     m_log.debug("creating new session");
554
555     time_t now = time(NULL);
556     auto_ptr_char index(session_index);
557     auto_ptr_char entity_id(issuer ? issuer->getEntityID() : NULL);
558     auto_ptr_char name(nameid ? nameid->getName() : NULL);
559
560     if (nameid) {
561         // Check for a pending logout.
562         if (strlen(name.get()) > 255)
563             const_cast<char*>(name.get())[255] = 0;
564         string pending;
565         int ver = m_storage->readText("Logout", name.get(), &pending);
566         if (ver > 0) {
567             DDF pendobj;
568             DDFJanitor jpend(pendobj);
569             istringstream pstr(pending);
570             pstr >> pendobj;
571             // IdP.SP.index contains logout expiration, if any.
572             DDF deadmenwalking = pendobj[issuer ? entity_id.get() : "_shibnull"][application.getString("entityID").second];
573             const char* logexpstr = deadmenwalking[session_index ? index.get() : "_shibnull"].string();
574             if (!logexpstr && session_index)    // we tried an exact session match, now try for NULL
575                 logexpstr = deadmenwalking["_shibnull"].string();
576             if (logexpstr) {
577                 auto_ptr_XMLCh dt(logexpstr);
578                 DateTime dtobj(dt.get());
579                 dtobj.parseDateTime();
580                 time_t logexp = dtobj.getEpoch();
581                 if (now - XMLToolingConfig::getConfig().clock_skew_secs < logexp)
582                     throw FatalProfileException("A logout message from your identity provider has blocked your login attempt.");
583             }
584         }
585     }
586
587     auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());
588
589     // Store session properties in DDF.
590     DDF obj = DDF(key.get()).structure();
591     obj.addmember("version").integer(1);
592     obj.addmember("application_id").string(application.getId());
593
594     // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
595 #ifndef HAVE_GMTIME_R
596     struct tm* ptime=gmtime(&expires);
597 #else
598     struct tm res;
599     struct tm* ptime=gmtime_r(&expires,&res);
600 #endif
601     char timebuf[32];
602     strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
603     obj.addmember("expires").string(timebuf);
604
605     if (client_addr)
606         obj.addmember("client_addr").string(client_addr);
607     if (issuer)
608         obj.addmember("entity_id").string(entity_id.get());
609     if (protocol) {
610         auto_ptr_char prot(protocol);
611         obj.addmember("protocol").string(prot.get());
612     }
613     if (authn_instant) {
614         auto_ptr_char instant(authn_instant);
615         obj.addmember("authn_instant").string(instant.get());
616     }
617     if (session_index)
618         obj.addmember("session_index").string(index.get());
619     if (authncontext_class) {
620         auto_ptr_char ac(authncontext_class);
621         obj.addmember("authncontext_class").string(ac.get());
622     }
623     if (authncontext_decl) {
624         auto_ptr_char ad(authncontext_decl);
625         obj.addmember("authncontext_decl").string(ad.get());
626     }
627
628     if (nameid) {
629         ostringstream namestr;
630         namestr << *nameid;
631         obj.addmember("nameid").string(namestr.str().c_str());
632     }
633
634     if (tokens) {
635         obj.addmember("assertions").list();
636         for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
637             auto_ptr_char tokenid((*t)->getID());
638             DDF tokid = DDF(NULL).string(tokenid.get());
639             obj["assertions"].add(tokid);
640         }
641     }
642     
643     if (attributes) {
644         DDF attr;
645         DDF attrlist = obj.addmember("attributes").list();
646         for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {
647             attr = (*a)->marshall();
648             attrlist.add(attr);
649         }
650     }
651     
652     ostringstream record;
653     record << obj;
654     
655     m_log.debug("storing new session...");
656     if (!m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout))
657         throw FatalProfileException("Attempted to create a session with a duplicate key.");
658     
659     // Store the reverse mapping for logout.
660     try {
661         if (nameid)
662             insert(key.get(), expires, name.get(), index.get());
663     }
664     catch (exception& ex) {
665         m_log.error("error storing back mapping of NameID for logout: %s", ex.what());
666     }
667
668     if (tokens) {
669         try {
670             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
671                 ostringstream tokenstr;
672                 tokenstr << *(*t);
673                 auto_ptr_char tokenid((*t)->getID());
674                 if (!m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout))
675                     throw IOException("duplicate assertion ID ($1)", params(1, tokenid.get()));
676             }
677         }
678         catch (exception& ex) {
679             m_log.error("error storing assertion along with session: %s", ex.what());
680         }
681     }
682
683     const char* pid = obj["entity_id"].string();
684     m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);
685
686     // Transaction Logging
687     TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
688     Locker locker(xlog);
689     xlog->log.infoStream() <<
690         "New session (ID: " <<
691             key.get() <<
692         ") with (applicationId: " <<
693             application.getId() <<
694         ") for principal from (IdP: " <<
695             (pid ? pid : "none") <<
696         ") at (ClientAddress: " <<
697             (client_addr ? client_addr : "none") <<
698         ") with (NameIdentifier: " <<
699             (nameid ? name.get() : "none") <<
700         ")";
701     
702     if (attributes) {
703         xlog->log.infoStream() <<
704             "Cached the following attributes with session (ID: " <<
705                 key.get() <<
706             ") for (applicationId: " <<
707                 application.getId() <<
708             ") {";
709         for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)
710             xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";
711         xlog->log.info("}");
712     }
713
714     return key.get();
715 }
716
717 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
718 {
719 #ifdef _DEBUG
720     xmltooling::NDC ndc("find");
721 #endif
722
723     m_log.debug("searching for session (%s)", key);
724     
725     time_t lastAccess;
726     string record;
727     int ver = m_storage->readText(key, "session", &record, &lastAccess);
728     if (!ver)
729         return NULL;
730     
731     m_log.debug("reconstituting session and checking validity");
732     
733     DDF obj;
734     istringstream in(record);
735     in >> obj;
736     
737     if (!XMLString::equals(obj["application_id"].string(), application.getId())) {
738         m_log.error("an application (%s) tried to access another application's session", application.getId());
739         obj.destroy();
740         return NULL;
741     }
742
743     if (client_addr) {
744         if (m_log.isDebugEnabled())
745             m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());
746         if (strcmp(obj["client_addr"].string(),client_addr)) {
747             m_log.warn("client address mismatch");
748             remove(key, application);
749             RetryableProfileException ex(
750                 "Your IP address ($1) does not match the address recorded at the time the session was established.",
751                 params(1,client_addr)
752                 );
753             string eid(obj["entity_id"].string());
754             obj.destroy();
755             if (eid.empty())
756                 throw ex;
757             MetadataProvider* m=application.getMetadataProvider();
758             Locker locker(m);
759             annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
760         }
761     }
762
763     lastAccess -= m_cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched
764     time_t now=time(NULL);
765     
766     if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {
767         m_log.info("session timed out (ID: %s)", key);
768         remove(key, application);
769         RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
770         string eid(obj["entity_id"].string());
771         obj.destroy();
772         if (eid.empty())
773             throw ex;
774         MetadataProvider* m=application.getMetadataProvider();
775         Locker locker(m);
776         annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
777     }
778     
779     auto_ptr_XMLCh exp(obj["expires"].string());
780     if (exp.get()) {
781         DateTime iso(exp.get());
782         iso.parseDateTime();
783         if (now > iso.getEpoch()) {
784             m_log.info("session expired (ID: %s)", key);
785             remove(key, application);
786             RetryableProfileException ex("Your session has expired, and you must re-authenticate.");
787             string eid(obj["entity_id"].string());
788             obj.destroy();
789             if (eid.empty())
790                 throw ex;
791             MetadataProvider* m=application.getMetadataProvider();
792             Locker locker(m);
793             annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it
794         }
795     }
796     
797     if (timeout) {
798         // Update storage expiration, if possible.
799         try {
800             m_storage->updateContext(key, now + m_cacheTimeout);
801         }
802         catch (exception& ex) {
803             m_log.error("failed to update session expiration: %s", ex.what());
804         }
805     }
806
807     // Finally build the Session object.
808     try {
809         return new StoredSession(this, obj);
810     }
811     catch (exception&) {
812         obj.destroy();
813         throw;
814     }
815 }
816
817 void SSCache::remove(const char* key, const Application& application)
818 {
819 #ifdef _DEBUG
820     xmltooling::NDC ndc("remove");
821 #endif
822
823     m_storage->deleteContext(key);
824     m_log.info("removed session (%s)", key);
825
826     TransactionLog* xlog = application.getServiceProvider().getTransactionLog();
827     Locker locker(xlog);
828     xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);
829 }
830
831 bool SSCache::matches(
832     const char* key,
833     const saml2md::EntityDescriptor* issuer,
834     const saml2::NameID& nameid,
835     const set<string>* indexes,
836     const Application& application
837     )
838 {
839     auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
840     try {
841         Session* session = find(key, application);
842         if (session) {
843             Locker locker(session);
844             if (XMLString::equals(session->getEntityID(), entityID.get()) && session->getNameID() &&
845                     stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
846                 return (!indexes || indexes->empty() || (session->getSessionIndex() ? (indexes->count(session->getSessionIndex())>0) : false));
847             }
848         }
849     }
850     catch (exception& ex) {
851         m_log.error("error while matching session (%s): %s", key, ex.what());
852     }
853     return false;
854 }
855
856 vector<string>::size_type SSCache::logout(
857     const saml2md::EntityDescriptor* issuer,
858     const saml2::NameID& nameid,
859     const set<string>* indexes,
860     time_t expires,
861     const Application& application,
862     vector<string>& sessionsKilled
863     )
864 {
865 #ifdef _DEBUG
866     xmltooling::NDC ndc("logout");
867 #endif
868
869     auto_ptr_char entityID(issuer ? issuer->getEntityID() : NULL);
870     auto_ptr_char name(nameid.getName());
871
872     m_log.info("request to logout sessions from (%s) for (%s)", entityID.get() ? entityID.get() : "unknown", name.get());
873
874     if (strlen(name.get()) > 255)
875         const_cast<char*>(name.get())[255] = 0;
876
877     DDF obj;
878     DDFJanitor jobj(obj);
879     string record;
880     int ver;
881
882     if (expires) {
883         // Record the logout to prevent post-delivered assertions.
884         // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
885 #ifndef HAVE_GMTIME_R
886         struct tm* ptime=gmtime(&expires);
887 #else
888         struct tm res;
889         struct tm* ptime=gmtime_r(&expires,&res);
890 #endif
891         char timebuf[32];
892         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
893
894         time_t oldexp = 0;
895         ver = m_storage->readText("Logout", name.get(), &record, &oldexp);
896         if (ver > 0) {
897             istringstream lin(record);
898             lin >> obj;
899         }
900         else {
901             obj = DDF(NULL).structure();
902         }
903
904         // Structure is keyed by the IdP and SP, with a member per session index containing the expiration.
905         DDF root = obj.addmember(issuer ? entityID.get() : "_shibnull").addmember(application.getString("entityID").second);
906         if (indexes) {
907             for (set<string>::const_iterator x = indexes->begin(); x!=indexes->end(); ++x)
908                 root.addmember(x->c_str()).string(timebuf);
909         }
910         else {
911             root.addmember("_shibnull").string(timebuf);
912         }
913
914         // Write it back.
915         ostringstream lout;
916         lout << obj;
917
918         if (ver > 0) {
919             ver = m_storage->updateText("Logout", name.get(), lout.str().c_str(), max(expires, oldexp), ver);
920             if (ver <= 0) {
921                 // Out of sync, or went missing, so retry.
922                 return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
923             }
924         }
925         else if (!m_storage->createText("Logout", name.get(), lout.str().c_str(), expires)) {
926             // Hit a dup, so just retry, hopefully hitting the other branch.
927             return logout(issuer, nameid, indexes, expires, application, sessionsKilled);
928         }
929
930         obj.destroy();
931         record.erase();
932     }
933
934     // Read in potentially matching sessions.
935     ver = m_storage->readText("NameID", name.get(), &record);
936     if (ver == 0) {
937         m_log.debug("no active sessions to logout for supplied issuer and subject");
938         return 0;
939     }
940
941     istringstream in(record);
942     in >> obj;
943
944     // The record contains child lists for each known session index.
945     DDF key;
946     DDF sessions = obj.first();
947     while (sessions.islist()) {
948         if (!indexes || indexes->empty() || indexes->count(sessions.name())) {
949             key = sessions.first();
950             while (key.isstring()) {
951                 // Fetch the session for comparison.
952                 Session* session = NULL;
953                 try {
954                     session = find(key.string(), application);
955                 }
956                 catch (exception& ex) {
957                     m_log.error("error locating session (%s): %s", key.string(), ex.what());
958                 }
959
960                 if (session) {
961                     Locker locker(session);
962                     // Same issuer?
963                     if (XMLString::equals(session->getEntityID(), entityID.get())) {
964                         // Same NameID?
965                         if (stronglyMatches(issuer->getEntityID(), application.getXMLString("entityID").second, nameid, *session->getNameID())) {
966                             sessionsKilled.push_back(key.string());
967                             key.destroy();
968                         }
969                         else {
970                             m_log.debug("session (%s) contained a non-matching NameID, leaving it alone", key.string());
971                         }
972                     }
973                     else {
974                         m_log.debug("session (%s) established by different IdP, leaving it alone", key.string());
975                     }
976                 }
977                 else {
978                     // Session's gone, so...
979                     sessionsKilled.push_back(key.string());
980                     key.destroy();
981                 }
982                 key = sessions.next();
983             }
984
985             // No sessions left for this index?
986             if (sessions.first().isnull())
987                 sessions.destroy();
988         }
989         sessions = obj.next();
990     }
991     
992     if (obj.first().isnull())
993         obj.destroy();
994
995     // If possible, write back the mapping record (this isn't crucial).
996     try {
997         if (obj.isnull()) {
998             m_storage->deleteText("NameID", name.get());
999         }
1000         else if (!sessionsKilled.empty()) {
1001             ostringstream out;
1002             out << obj;
1003             if (m_storage->updateText("NameID", name.get(), out.str().c_str(), 0, ver) <= 0)
1004                 m_log.warn("logout mapping record changed behind us, leaving it alone");
1005         }
1006     }
1007     catch (exception& ex) {
1008         m_log.error("error updating logout mapping record: %s", ex.what());
1009     }
1010
1011     return sessionsKilled.size();
1012 }
1013
1014 bool SSCache::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
1015 {
1016     if (!XMLString::equals(n1.getName(), n2.getName()))
1017         return false;
1018     
1019     const XMLCh* s1 = n1.getFormat();
1020     const XMLCh* s2 = n2.getFormat();
1021     if (!s1 || !*s1)
1022         s1 = saml2::NameID::UNSPECIFIED;
1023     if (!s2 || !*s2)
1024         s2 = saml2::NameID::UNSPECIFIED;
1025     if (!XMLString::equals(s1,s2))
1026         return false;
1027     
1028     s1 = n1.getNameQualifier();
1029     s2 = n2.getNameQualifier();
1030     if (!s1 || !*s1)
1031         s1 = idp;
1032     if (!s2 || !*s2)
1033         s2 = idp;
1034     if (!XMLString::equals(s1,s2))
1035         return false;
1036
1037     s1 = n1.getSPNameQualifier();
1038     s2 = n2.getSPNameQualifier();
1039     if (!s1 || !*s1)
1040         s1 = sp;
1041     if (!s2 || !*s2)
1042         s2 = sp;
1043     if (!XMLString::equals(s1,s2))
1044         return false;
1045
1046     return true;
1047 }
1048
1049 void SSCache::receive(DDF& in, ostream& out)
1050 {
1051 #ifdef _DEBUG
1052     xmltooling::NDC ndc("receive");
1053 #endif
1054
1055     if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {
1056         const char* key=in["key"].string();
1057         if (!key)
1058             throw ListenerException("Required parameters missing for session removal.");
1059
1060         const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1061         if (!app)
1062             throw ListenerException("Application not found, check configuration?");
1063
1064         // Do an unversioned read.
1065         string record;
1066         time_t lastAccess;
1067         if (!m_storage->readText(key, "session", &record, &lastAccess)) {
1068             DDF ret(NULL);
1069             DDFJanitor jan(ret);
1070             out << ret;
1071             return;
1072         }
1073
1074         // Adjust for expiration to recover last access time and check timeout.
1075         lastAccess -= m_cacheTimeout;
1076         time_t now=time(NULL);
1077
1078         // See if we need to check for a timeout.
1079         if (in["timeout"].string()) {
1080             time_t timeout = 0;
1081             auto_ptr_XMLCh dt(in["timeout"].string());
1082             DateTime dtobj(dt.get());
1083             dtobj.parseDateTime();
1084             timeout = dtobj.getEpoch();
1085                     
1086             if (timeout > 0 && now - lastAccess >= timeout) {
1087                 m_log.info("session timed out (ID: %s)", key);
1088                 remove(key,*app);
1089                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1090             } 
1091
1092             // Update storage expiration, if possible.
1093             try {
1094                 m_storage->updateContext(key, now + m_cacheTimeout);
1095             }
1096             catch (exception& ex) {
1097                 m_log.error("failed to update session expiration: %s", ex.what());
1098             }
1099         }
1100             
1101         // Send the record back.
1102         out << record;
1103     }
1104     else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {
1105         const char* key=in["key"].string();
1106         if (!key)
1107             throw ListenerException("Required parameters missing for session check.");
1108
1109         // Do a versioned read.
1110         string record;
1111         time_t lastAccess;
1112         int curver = in["version"].integer();
1113         int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);
1114         if (ver == 0) {
1115             m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);
1116             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1117         }
1118
1119         // Adjust for expiration to recover last access time and check timeout.
1120         lastAccess -= m_cacheTimeout;
1121         time_t now=time(NULL);
1122
1123         // See if we need to check for a timeout.
1124         time_t timeout = 0;
1125         auto_ptr_XMLCh dt(in["timeout"].string());
1126         if (dt.get()) {
1127             DateTime dtobj(dt.get());
1128             dtobj.parseDateTime();
1129             timeout = dtobj.getEpoch();
1130         }
1131                 
1132         if (timeout > 0 && now - lastAccess >= timeout) {
1133             m_log.info("session timed out (ID: %s)", key);
1134             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");
1135         } 
1136
1137         // Update storage expiration, if possible.
1138         try {
1139             m_storage->updateContext(key, now + m_cacheTimeout);
1140         }
1141         catch (exception& ex) {
1142             m_log.error("failed to update session expiration: %s", ex.what());
1143         }
1144             
1145         if (ver > curver) {
1146             // Send the record back.
1147             out << record;
1148         }
1149         else {
1150             DDF ret(NULL);
1151             DDFJanitor jan(ret);
1152             out << ret;
1153         }
1154     }
1155     else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {
1156         const char* key=in["key"].string();
1157         if (!key)
1158             throw ListenerException("Required parameter missing for session removal.");
1159
1160         const Application* app = SPConfig::getConfig().getServiceProvider()->getApplication(in["application_id"].string());
1161         if (!app)
1162             throw ListenerException("Application not found, check configuration?");
1163
1164         remove(key,*app);
1165         DDF ret(NULL);
1166         DDFJanitor jan(ret);
1167         out << ret;
1168     }
1169     else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {
1170         const char* key=in["key"].string();
1171         const char* id=in["id"].string();
1172         if (!key || !id)
1173             throw ListenerException("Required parameters missing for assertion retrieval.");
1174         string token;
1175         if (!m_storage->readText(key, id, &token, NULL))
1176             throw FatalProfileException("Assertion not found in cache.");
1177         out << token;
1178     }
1179 }