Change ownership of attributes input to cache.
[shibboleth/cpp-sp.git] / shibsp / impl / StorageServiceSessionCache.cpp
1 /*\r
2  *  Copyright 2001-2007 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * StorageServiceSessionCache.cpp\r
19  * \r
20  * StorageService-based SessionCache implementation.\r
21  * \r
22  * Instead of optimizing this plugin with a buffering scheme that keeps objects around\r
23  * and avoids extra parsing steps, I'm assuming that systems that require such can\r
24  * layer their own cache plugin on top of this version either by delegating to it\r
25  * or using the remoting support. So this version will load sessions directly\r
26  * from the StorageService, instantiate enough to expose the Session API,\r
27  * and then delete everything when they're unlocked. All data in memory is always\r
28  * kept in sync with the StorageService (no lazy updates).\r
29  */\r
30 \r
31 #include "internal.h"\r
32 #include "Application.h"\r
33 #include "exceptions.h"\r
34 #include "ServiceProvider.h"\r
35 #include "SessionCache.h"\r
36 #include "TransactionLog.h"\r
37 #include "attribute/Attribute.h"\r
38 #include "remoting/ListenerService.h"\r
39 #include "util/SPConstants.h"\r
40 \r
41 #include <log4cpp/Category.hh>\r
42 #include <saml/SAMLConfig.h>\r
43 #include <xmltooling/util/NDC.h>\r
44 #include <xmltooling/util/StorageService.h>\r
45 #include <xmltooling/util/XMLHelper.h>\r
46 #include <xercesc/util/XMLUniDefs.hpp>\r
47 \r
48 using namespace shibsp;\r
49 using namespace opensaml::saml2md;\r
50 using namespace opensaml;\r
51 using namespace xmltooling;\r
52 using namespace log4cpp;\r
53 using namespace std;\r
54 \r
55 namespace shibsp {\r
56 \r
57     class SSCache;\r
58     class StoredSession : public virtual Session\r
59     {\r
60     public:\r
61         StoredSession(SSCache* cache, DDF& obj) : m_obj(obj), m_nameid(NULL), m_cache(cache) {\r
62             const char* nameid = obj["nameid"].string();\r
63             if (nameid) {\r
64                 // Parse and bind the document into an XMLObject.\r
65                 istringstream instr(nameid);\r
66                 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
67                 XercesJanitor<DOMDocument> janitor(doc);\r
68                 auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());\r
69                 n->unmarshall(doc->getDocumentElement(), true);\r
70                 janitor.release();\r
71                 m_nameid = n.release();\r
72             }\r
73         }\r
74         \r
75         ~StoredSession();\r
76         \r
77         Lockable* lock() {\r
78             return this;\r
79         }\r
80         void unlock() {\r
81             delete this;\r
82         }\r
83         \r
84         const char* getID() const {\r
85             return m_obj.name();\r
86         }\r
87         const char* getClientAddress() const {\r
88             return m_obj["client_addr"].string();\r
89         }\r
90         const char* getEntityID() const {\r
91             return m_obj["entity_id"].string();\r
92         }\r
93         const char* getAuthnInstant() const {\r
94             return m_obj["authn_instant"].string();\r
95         }\r
96         const opensaml::saml2::NameID* getNameID() const {\r
97             return m_nameid;\r
98         }\r
99         const char* getSessionIndex() const {\r
100             return m_obj["session_index"].string();\r
101         }\r
102         const char* getAuthnContextClassRef() const {\r
103             return m_obj["authncontext_class"].string();\r
104         }\r
105         const char* getAuthnContextDeclRef() const {\r
106             return m_obj["authncontext_decl"].string();\r
107         }\r
108         const multimap<string,Attribute*>& getAttributes() const {\r
109             if (m_attributes.empty())\r
110                 unmarshallAttributes();\r
111             return m_attributes;\r
112         }\r
113         const vector<const char*>& getAssertionIDs() const {\r
114             if (m_ids.empty()) {\r
115                 DDF ids = m_obj["assertions"];\r
116                 DDF id = ids.first();\r
117                 while (id.isstring()) {\r
118                     m_ids.push_back(id.string());\r
119                     id = ids.next();\r
120                 }\r
121             }\r
122             return m_ids;\r
123         }\r
124         \r
125         void addAttributes(const vector<Attribute*>& attributes);\r
126         const Assertion* getAssertion(const char* id) const;\r
127         void addAssertion(Assertion* assertion);\r
128 \r
129     private:\r
130         void unmarshallAttributes() const;\r
131 \r
132         DDF m_obj;\r
133         saml2::NameID* m_nameid;\r
134         mutable multimap<string,Attribute*> m_attributes;\r
135         mutable vector<const char*> m_ids;\r
136         mutable map<string,Assertion*> m_tokens;\r
137         SSCache* m_cache;\r
138     };\r
139     \r
140     class SSCache : public SessionCache, public virtual Remoted\r
141     {\r
142     public:\r
143         SSCache(const DOMElement* e);\r
144         ~SSCache();\r
145     \r
146         void receive(DDF& in, ostream& out);\r
147         \r
148         string insert(\r
149             time_t expires,\r
150             const Application& application,\r
151             const char* client_addr=NULL,\r
152             const saml2md::EntityDescriptor* issuer=NULL,\r
153             const saml2::NameID* nameid=NULL,\r
154             const char* authn_instant=NULL,\r
155             const char* session_index=NULL,\r
156             const char* authncontext_class=NULL,\r
157             const char* authncontext_decl=NULL,\r
158             const vector<const Assertion*>* tokens=NULL,\r
159             const multimap<string,Attribute*>* attributes=NULL\r
160             );\r
161         Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);\r
162         void remove(const char* key, const Application& application, const char* client_addr);\r
163 \r
164         Category& m_log;\r
165         StorageService* m_storage;\r
166     };\r
167 \r
168     SessionCache* SHIBSP_DLLLOCAL StorageServiceCacheFactory(const DOMElement* const & e)\r
169     {\r
170         return new SSCache(e);\r
171     }\r
172 \r
173     static const XMLCh _StorageService[] =   UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
174 }\r
175 \r
176 StoredSession::~StoredSession()\r
177 {\r
178     m_obj.destroy();\r
179     delete m_nameid;\r
180     for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());\r
181     for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,Assertion>());\r
182 }\r
183 \r
184 void StoredSession::unmarshallAttributes() const\r
185 {\r
186     Attribute* attribute;\r
187     DDF attrs = m_obj["attributes"];\r
188     DDF attr = attrs.first();\r
189     while (!attr.isnull()) {\r
190         try {\r
191             attribute = Attribute::unmarshall(attr);\r
192             m_attributes.insert(make_pair(attribute->getId(), attribute));\r
193             if (m_cache->m_log.isDebugEnabled())\r
194                 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",\r
195                     attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");\r
196         }\r
197         catch (AttributeException& ex) {\r
198             const char* id = attr.first().name();\r
199             m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());\r
200         }\r
201         attr = attrs.next();\r
202     }\r
203 }\r
204 \r
205 void StoredSession::addAttributes(const vector<Attribute*>& attributes)\r
206 {\r
207 #ifdef _DEBUG\r
208     xmltooling::NDC ndc("addAttributes");\r
209 #endif\r
210 \r
211     m_cache->m_log.debug("adding attributes to session (%s)", getID());\r
212     \r
213     int ver;\r
214     do {\r
215         DDF attr;\r
216         DDF attrs = m_obj["attributes"];\r
217         if (!attrs.islist())\r
218             attrs = m_obj.addmember("attributes").list();\r
219         for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {\r
220             attr = (*a)->marshall();\r
221             attrs.add(attr);\r
222         }\r
223         \r
224         // Tentatively increment the version.\r
225         m_obj["version"].integer(m_obj["version"].integer()+1);\r
226         \r
227         ostringstream str;\r
228         str << m_obj;\r
229         string record(str.str()); \r
230 \r
231         try {\r
232             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
233         }\r
234         catch (exception&) {\r
235             // Roll back modification to record.\r
236             m_obj["version"].integer(m_obj["version"].integer()-1);\r
237             vector<Attribute*>::size_type count = attributes.size();\r
238             while (count--)\r
239                 attrs.last().destroy();            \r
240             throw;\r
241         }\r
242 \r
243         if (ver <= 0) {\r
244             // Roll back modification to record.\r
245             m_obj["version"].integer(m_obj["version"].integer()-1);\r
246             vector<Attribute*>::size_type count = attributes.size();\r
247             while (count--)\r
248                 attrs.last().destroy();            \r
249         }\r
250         if (!ver) {\r
251             // Fatal problem with update.\r
252             throw IOException("Unable to update stored session.");\r
253         }\r
254         else if (ver < 0) {\r
255             // Out of sync.\r
256             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
257             ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
258             if (!ver) {\r
259                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
260                 throw IOException("Unable to read back stored session.");\r
261             }\r
262             \r
263             // Reset object.\r
264             DDF newobj;\r
265             istringstream in(record);\r
266             in >> newobj;\r
267 \r
268             m_ids.clear();\r
269             for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
270             m_attributes.clear();\r
271             newobj["version"].integer(ver);\r
272             m_obj.destroy();\r
273             m_obj = newobj;\r
274 \r
275             ver = -1;\r
276         }\r
277     } while (ver < 0);  // negative indicates a sync issue so we retry\r
278 \r
279     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
280     Locker locker(xlog);\r
281     xlog->log.infoStream() <<\r
282         "Added the following attributes to session (ID: " <<\r
283             getID() <<\r
284         ") for (applicationId: " <<\r
285             m_obj["application_id"].string() <<\r
286         ") {";\r
287     for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a)\r
288         xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";\r
289     xlog->log.info("}");\r
290 \r
291     // We own them now, so clean them up.\r
292     for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());\r
293 }\r
294 \r
295 const Assertion* StoredSession::getAssertion(const char* id) const\r
296 {\r
297     map<string,Assertion*>::const_iterator i = m_tokens.find(id);\r
298     if (i!=m_tokens.end())\r
299         return i->second;\r
300     \r
301     string tokenstr;\r
302     if (!m_cache->m_storage->readText(getID(), id, &tokenstr, NULL))\r
303         throw FatalProfileException("Assertion not found in cache.");\r
304 \r
305     // Parse and bind the document into an XMLObject.\r
306     istringstream instr(tokenstr);\r
307     DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
308     XercesJanitor<DOMDocument> janitor(doc);\r
309     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
310     janitor.release();\r
311     \r
312     Assertion* token = dynamic_cast<Assertion*>(xmlObject.get());\r
313     if (!token)\r
314         throw FatalProfileException("Request for cached assertion returned an unknown object type.");\r
315 \r
316     // Transfer ownership to us.\r
317     xmlObject.release();\r
318     m_tokens[id]=token;\r
319     return token;\r
320 }\r
321 \r
322 void StoredSession::addAssertion(Assertion* assertion)\r
323 {\r
324 #ifdef _DEBUG\r
325     xmltooling::NDC ndc("addAssertion");\r
326 #endif\r
327     \r
328     if (!assertion)\r
329         throw FatalProfileException("Unknown object type passed to session for storage.");\r
330 \r
331     auto_ptr_char id(assertion->getID());\r
332 \r
333     m_cache->m_log.debug("adding assertion (%s) to session (%s)", id.get(), getID());\r
334 \r
335     time_t exp;\r
336     if (!m_cache->m_storage->readText(getID(), "session", NULL, &exp))\r
337         throw IOException("Unable to load expiration time for stored session.");\r
338 \r
339     ostringstream tokenstr;\r
340     tokenstr << *assertion;\r
341     m_cache->m_storage->createText(getID(), id.get(), tokenstr.str().c_str(), exp);\r
342     \r
343     int ver;\r
344     do {\r
345         DDF token = DDF(NULL).string(id.get());\r
346         m_obj["assertions"].add(token);\r
347 \r
348         // Tentatively increment the version.\r
349         m_obj["version"].integer(m_obj["version"].integer()+1);\r
350     \r
351         ostringstream str;\r
352         str << m_obj;\r
353         string record(str.str()); \r
354 \r
355         try {\r
356             ver = m_cache->m_storage->updateText(getID(), "session", record.c_str(), 0, m_obj["version"].integer()-1);\r
357         }\r
358         catch (exception&) {\r
359             token.destroy();\r
360             m_obj["version"].integer(m_obj["version"].integer()-1);\r
361             m_cache->m_storage->deleteText(getID(), id.get());\r
362             throw;\r
363         }\r
364 \r
365         if (ver <= 0) {\r
366             token.destroy();\r
367             m_obj["version"].integer(m_obj["version"].integer()-1);\r
368         }            \r
369         if (!ver) {\r
370             // Fatal problem with update.\r
371             m_cache->m_log.error("updateText failed on StorageService for session (%s)", getID());\r
372             m_cache->m_storage->deleteText(getID(), id.get());\r
373             throw IOException("Unable to update stored session.");\r
374         }\r
375         else if (ver < 0) {\r
376             // Out of sync.\r
377             m_cache->m_log.warn("storage service indicates the record is out of sync, updating with a fresh copy...");\r
378             ver = m_cache->m_storage->readText(getID(), "session", &record, NULL);\r
379             if (!ver) {\r
380                 m_cache->m_log.error("readText failed on StorageService for session (%s)", getID());\r
381                 m_cache->m_storage->deleteText(getID(), id.get());\r
382                 throw IOException("Unable to read back stored session.");\r
383             }\r
384             \r
385             // Reset object.\r
386             DDF newobj;\r
387             istringstream in(record);\r
388             in >> newobj;\r
389 \r
390             m_ids.clear();\r
391             for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
392             m_attributes.clear();\r
393             newobj["version"].integer(ver);\r
394             m_obj.destroy();\r
395             m_obj = newobj;\r
396             \r
397             ver = -1;\r
398         }\r
399     } while (ver < 0); // negative indicates a sync issue so we retry\r
400 \r
401     m_ids.clear();\r
402     delete assertion;\r
403 \r
404     TransactionLog* xlog = SPConfig::getConfig().getServiceProvider()->getTransactionLog();\r
405     Locker locker(xlog);\r
406     xlog->log.info(\r
407         "Added assertion (ID: %s) to session for (applicationId: %s) with (ID: %s)",\r
408         id.get(), m_obj["application_id"].string(), getID()\r
409         );\r
410 }\r
411 \r
412 SSCache::SSCache(const DOMElement* e)\r
413     : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_storage(NULL)\r
414 {\r
415     SPConfig& conf = SPConfig::getConfig();\r
416     const XMLCh* tag = e ? e->getAttributeNS(NULL,_StorageService) : NULL;\r
417     if (tag && *tag) {\r
418         auto_ptr_char ssid(tag);\r
419         m_storage = conf.getServiceProvider()->getStorageService(ssid.get());\r
420         if (m_storage)\r
421             m_log.info("bound to StorageService (%s)", ssid.get());\r
422         else\r
423             throw ConfigurationException("SessionCache unable to locate StorageService, check configuration.");\r
424     }\r
425 \r
426     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
427     if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
428         listener->regListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
429         listener->regListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
430         listener->regListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
431         listener->regListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
432     }\r
433     else {\r
434         m_log.info("no ListenerService available, cache remoting disabled");\r
435     }\r
436 }\r
437 \r
438 SSCache::~SSCache()\r
439 {\r
440     SPConfig& conf = SPConfig::getConfig();\r
441     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);\r
442     if (listener && conf.isEnabled(SPConfig::OutOfProcess)) {\r
443         listener->unregListener("find::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
444         listener->unregListener("remove::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
445         listener->unregListener("touch::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
446         listener->unregListener("getAssertion::"REMOTED_SESSION_CACHE"::SessionCache",this);\r
447     }\r
448 }\r
449 \r
450 string SSCache::insert(\r
451     time_t expires,\r
452     const Application& application,\r
453     const char* client_addr,\r
454     const saml2md::EntityDescriptor* issuer,\r
455     const saml2::NameID* nameid,\r
456     const char* authn_instant,\r
457     const char* session_index,\r
458     const char* authncontext_class,\r
459     const char* authncontext_decl,\r
460     const vector<const Assertion*>* tokens,\r
461     const multimap<string,Attribute*>* attributes\r
462     )\r
463 {\r
464 #ifdef _DEBUG\r
465     xmltooling::NDC ndc("insert");\r
466 #endif\r
467 \r
468     m_log.debug("creating new session");\r
469 \r
470     auto_ptr_char key(SAMLConfig::getConfig().generateIdentifier());\r
471 \r
472     // Store session properties in DDF.\r
473     DDF obj = DDF(key.get()).structure();\r
474     obj.addmember("version").integer(1);\r
475     obj.addmember("application_id").string(application.getId());\r
476     if (expires > 0) {\r
477         // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  \r
478 #ifndef HAVE_GMTIME_R\r
479         struct tm* ptime=gmtime(&expires);\r
480 #else\r
481         struct tm res;\r
482         struct tm* ptime=gmtime_r(&expires,&res);\r
483 #endif\r
484         char timebuf[32];\r
485         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
486         obj.addmember("expires").string(timebuf);\r
487     }\r
488     if (client_addr)\r
489         obj.addmember("client_addr").string(client_addr);\r
490     if (issuer) {\r
491         auto_ptr_char entity_id(issuer->getEntityID());\r
492         obj.addmember("entity_id").string(entity_id.get());\r
493     }\r
494     if (authn_instant)\r
495         obj.addmember("authn_instant").string(authn_instant);\r
496     if (session_index)\r
497         obj.addmember("session_index").string(session_index);\r
498     if (authncontext_class)\r
499         obj.addmember("authncontext_class").string(authncontext_class);\r
500     if (authncontext_decl)\r
501         obj.addmember("authncontext_decl").string(authncontext_decl);\r
502 \r
503     if (nameid) {\r
504         ostringstream namestr;\r
505         namestr << *nameid;\r
506         obj.addmember("nameid").string(namestr.str().c_str());\r
507     }\r
508 \r
509     if (tokens) {\r
510         obj.addmember("assertions").list();\r
511         for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
512             auto_ptr_char tokenid((*t)->getID());\r
513             DDF tokid = DDF(NULL).string(tokenid.get());\r
514             obj["assertions"].add(tokid);\r
515         }\r
516     }\r
517     \r
518     if (attributes) {\r
519         DDF attr;\r
520         DDF attrlist = obj.addmember("attributes").list();\r
521         for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {\r
522             attr = a->second->marshall();\r
523             attrlist.add(attr);\r
524         }\r
525     }\r
526     \r
527     ostringstream record;\r
528     record << obj;\r
529     \r
530     m_log.debug("storing new session...");\r
531     time_t now = time(NULL);\r
532     m_storage->createText(key.get(), "session", record.str().c_str(), now + m_cacheTimeout);\r
533     if (tokens) {\r
534         try {\r
535             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {\r
536                 ostringstream tokenstr;\r
537                 tokenstr << *(*t);\r
538                 auto_ptr_char tokenid((*t)->getID());\r
539                 m_storage->createText(key.get(), tokenid.get(), tokenstr.str().c_str(), now + m_cacheTimeout);\r
540             }\r
541         }\r
542         catch (exception& ex) {\r
543             m_log.error("error storing assertion along with session: %s", ex.what());\r
544         }\r
545     }\r
546 \r
547     const char* pid = obj["entity_id"].string();\r
548     m_log.info("new session created: SessionID (%s) IdP (%s) Address (%s)", key.get(), pid ? pid : "none", client_addr);\r
549 \r
550     // Transaction Logging\r
551     auto_ptr_char name(nameid ? nameid->getName() : NULL);\r
552     TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
553     Locker locker(xlog);\r
554     xlog->log.infoStream() <<\r
555         "New session (ID: " <<\r
556             key.get() <<\r
557         ") with (applicationId: " <<\r
558             application.getId() <<\r
559         ") for principal from (IdP: " <<\r
560             (pid ? pid : "none") <<\r
561         ") at (ClientAddress: " <<\r
562             (client_addr ? client_addr : "none") <<\r
563         ") with (NameIdentifier: " <<\r
564             (name.get() ? name.get() : "none") <<\r
565         ")";\r
566     \r
567     if (attributes) {\r
568         xlog->log.infoStream() <<\r
569             "Cached the following attributes with session (ID: " <<\r
570                 key.get() <<\r
571             ") for (applicationId: " <<\r
572                 application.getId() <<\r
573             ") {";\r
574         for (multimap<string,Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)\r
575             xlog->log.infoStream() << "\t" << a->second->getId() << " (" << a->second->valueCount() << " values)";\r
576         xlog->log.info("}");\r
577     }\r
578 \r
579     return key.get();\r
580 }\r
581 \r
582 Session* SSCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)\r
583 {\r
584 #ifdef _DEBUG\r
585     xmltooling::NDC ndc("find");\r
586 #endif\r
587 \r
588     m_log.debug("searching for session (%s)", key);\r
589     \r
590     time_t lastAccess;\r
591     string record;\r
592     int ver = m_storage->readText(key, "session", &record, &lastAccess);\r
593     if (!ver)\r
594         return NULL;\r
595     \r
596     m_log.debug("reconstituting session and checking validity");\r
597     \r
598     DDF obj;\r
599     istringstream in(record);\r
600     in >> obj;\r
601     \r
602     if (!XMLString::equals(obj["application_id"].string(), application.getId())) {\r
603         m_log.error("an application (%s) tried to access another application's session", application.getId());\r
604         obj.destroy();\r
605         return NULL;\r
606     }\r
607 \r
608     if (client_addr) {\r
609         if (m_log.isDebugEnabled())\r
610             m_log.debug("comparing client address %s against %s", client_addr, obj["client_addr"].string());\r
611         if (strcmp(obj["client_addr"].string(),client_addr)) {\r
612             m_log.warn("client address mismatch");\r
613             remove(key, application, client_addr);\r
614             RetryableProfileException ex(\r
615                 "Your IP address ($1) does not match the address recorded at the time the session was established.",\r
616                 params(1,client_addr)\r
617                 );\r
618             string eid(obj["entity_id"].string());\r
619             obj.destroy();\r
620             if (eid.empty())\r
621                 throw ex;\r
622             MetadataProvider* m=application.getMetadataProvider();\r
623             Locker locker(m);\r
624             annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
625         }\r
626     }\r
627 \r
628     lastAccess -= m_cacheTimeout;   // adjusts it back to the last time the record's timestamp was touched\r
629     time_t now=time(NULL);\r
630     \r
631     if (timeout && *timeout > 0 && now - lastAccess >= *timeout) {\r
632         m_log.info("session timed out (ID: %s)", key);\r
633         remove(key, application, client_addr);\r
634         RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
635         string eid(obj["entity_id"].string());\r
636         obj.destroy();\r
637         if (eid.empty())\r
638             throw ex;\r
639         MetadataProvider* m=application.getMetadataProvider();\r
640         Locker locker(m);\r
641         annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
642     }\r
643     \r
644     auto_ptr_XMLCh exp(obj["expires"].string());\r
645     if (exp.get()) {\r
646         DateTime iso(exp.get());\r
647         iso.parseDateTime();\r
648         if (now > iso.getEpoch()) {\r
649             m_log.info("session expired (ID: %s)", key);\r
650             remove(key, application, client_addr);\r
651             RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
652             string eid(obj["entity_id"].string());\r
653             obj.destroy();\r
654             if (eid.empty())\r
655                 throw ex;\r
656             MetadataProvider* m=application.getMetadataProvider();\r
657             Locker locker(m);\r
658             annotateException(&ex,m->getEntityDescriptor(eid.c_str(),false)); // throws it\r
659         }\r
660     }\r
661     \r
662     if (timeout) {\r
663         // Update storage expiration, if possible.\r
664         try {\r
665             m_storage->updateContext(key, now + m_cacheTimeout);\r
666         }\r
667         catch (exception& ex) {\r
668             m_log.error("failed to update session expiration: %s", ex.what());\r
669         }\r
670     }\r
671 \r
672     // Finally build the Session object.\r
673     try {\r
674         return new StoredSession(this, obj);\r
675     }\r
676     catch (exception&) {\r
677         obj.destroy();\r
678         throw;\r
679     }\r
680 }\r
681 \r
682 void SSCache::remove(const char* key, const Application& application, const char* client_addr)\r
683 {\r
684 #ifdef _DEBUG\r
685     xmltooling::NDC ndc("remove");\r
686 #endif\r
687 \r
688     m_storage->deleteContext(key);\r
689     m_log.info("removed session (%s)", key);\r
690 \r
691     TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
692     Locker locker(xlog);\r
693     xlog->log.info("Destroyed session (applicationId: %s) (ID: %s)", application.getId(), key);\r
694 }\r
695 \r
696 void SSCache::receive(DDF& in, ostream& out)\r
697 {\r
698 #ifdef _DEBUG\r
699     xmltooling::NDC ndc("receive");\r
700 #endif\r
701 \r
702     if (!strcmp(in.name(),"find::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
703         const char* key=in["key"].string();\r
704         if (!key)\r
705             throw ListenerException("Required parameters missing for session removal.");\r
706 \r
707         // Do an unversioned read.\r
708         string record;\r
709         time_t lastAccess;\r
710         if (!m_storage->readText(key, "session", &record, &lastAccess)) {\r
711             DDF ret(NULL);\r
712             DDFJanitor jan(ret);\r
713             out << ret;\r
714             return;\r
715         }\r
716 \r
717         // Adjust for expiration to recover last access time and check timeout.\r
718         lastAccess -= m_cacheTimeout;\r
719         time_t now=time(NULL);\r
720 \r
721         // See if we need to check for a timeout.\r
722         if (in["timeout"].string()) {\r
723             time_t timeout = 0;\r
724             auto_ptr_XMLCh dt(in["timeout"].string());\r
725             DateTime dtobj(dt.get());\r
726             dtobj.parseDateTime();\r
727             timeout = dtobj.getEpoch();\r
728                     \r
729             if (timeout > 0 && now - lastAccess >= timeout) {\r
730                 m_log.info("session timed out (ID: %s)", key);\r
731                 remove(key,*(SPConfig::getConfig().getServiceProvider()->getApplication("default")),NULL);\r
732                 throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
733             } \r
734 \r
735             // Update storage expiration, if possible.\r
736             try {\r
737                 m_storage->updateContext(key, now + m_cacheTimeout);\r
738             }\r
739             catch (exception& ex) {\r
740                 m_log.error("failed to update session expiration: %s", ex.what());\r
741             }\r
742         }\r
743             \r
744         // Send the record back.\r
745         out << record;\r
746     }\r
747     else if (!strcmp(in.name(),"touch::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
748         const char* key=in["key"].string();\r
749         if (!key)\r
750             throw ListenerException("Required parameters missing for session check.");\r
751 \r
752         // Do a versioned read.\r
753         string record;\r
754         time_t lastAccess;\r
755         int curver = in["version"].integer();\r
756         int ver = m_storage->readText(key, "session", &record, &lastAccess, curver);\r
757         if (ver == 0) {\r
758             m_log.warn("unsuccessful versioned read of session (ID: %s), caches out of sync?", key);\r
759             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
760         }\r
761 \r
762         // Adjust for expiration to recover last access time and check timeout.\r
763         lastAccess -= m_cacheTimeout;\r
764         time_t now=time(NULL);\r
765 \r
766         // See if we need to check for a timeout.\r
767         time_t timeout = 0;\r
768         auto_ptr_XMLCh dt(in["timeout"].string());\r
769         if (dt.get()) {\r
770             DateTime dtobj(dt.get());\r
771             dtobj.parseDateTime();\r
772             timeout = dtobj.getEpoch();\r
773         }\r
774                 \r
775         if (timeout > 0 && now - lastAccess >= timeout) {\r
776             m_log.info("session timed out (ID: %s)", key);\r
777             throw RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
778         } \r
779 \r
780         // Update storage expiration, if possible.\r
781         try {\r
782             m_storage->updateContext(key, now + m_cacheTimeout);\r
783         }\r
784         catch (exception& ex) {\r
785             m_log.error("failed to update session expiration: %s", ex.what());\r
786         }\r
787             \r
788         if (ver > curver) {\r
789             // Send the record back.\r
790             out << record;\r
791         }\r
792         else {\r
793             DDF ret(NULL);\r
794             DDFJanitor jan(ret);\r
795             out << ret;\r
796         }\r
797     }\r
798     else if (!strcmp(in.name(),"remove::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
799         const char* key=in["key"].string();\r
800         if (!key)\r
801             throw ListenerException("Required parameter missing for session removal.");\r
802         \r
803         remove(key,*(SPConfig::getConfig().getServiceProvider()->getApplication("default")),NULL);\r
804         DDF ret(NULL);\r
805         DDFJanitor jan(ret);\r
806         out << ret;\r
807     }\r
808     else if (!strcmp(in.name(),"getAssertion::"REMOTED_SESSION_CACHE"::SessionCache")) {\r
809         const char* key=in["key"].string();\r
810         const char* id=in["id"].string();\r
811         if (!key || !id)\r
812             throw ListenerException("Required parameters missing for assertion retrieval.");\r
813         string token;\r
814         if (!m_storage->readText(key, id, &token, NULL))\r
815             throw FatalProfileException("Assertion not found in cache.");\r
816         out << token;\r
817     }\r
818 }\r