2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * RemotedSessionCache.cpp
20 * SessionCache implementation that delegates to a remoted version.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "attribute/Attribute.h"
29 #include "remoting/ListenerService.h"
30 #include "util/SPConstants.h"
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/util/DateTime.h>
36 #include <xmltooling/util/NDC.h>
37 #include <xmltooling/util/XMLHelper.h>
39 using namespace shibsp;
40 using namespace xmltooling;
46 class RemotedSession : public virtual Session
49 RemotedSession(RemotedCache* cache, DDF& obj) : m_version(obj["version"].integer()), m_obj(obj),
50 m_expires(0), m_lastAccess(time(NULL)), m_cache(cache), m_lock(NULL) {
51 auto_ptr_XMLCh exp(m_obj["expires"].string());
53 DateTime iso(exp.get());
55 m_expires = iso.getEpoch();
58 m_lock = Mutex::create();
64 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
75 const char* getID() const {
78 const char* getApplicationID() const {
79 return m_obj["application_id"].string();
81 const char* getClientAddress() const {
82 return m_obj["client_addr"].string();
84 const char* getEntityID() const {
85 return m_obj["entity_id"].string();
87 const char* getProtocol() const {
88 return m_obj["protocol"].string();
90 const char* getAuthnInstant() const {
91 return m_obj["authn_instant"].string();
93 const char* getSessionIndex() const {
94 return m_obj["session_index"].string();
96 const char* getAuthnContextClassRef() const {
97 return m_obj["authncontext_class"].string();
99 const char* getAuthnContextDeclRef() const {
100 return m_obj["authncontext_decl"].string();
102 const vector<Attribute*>& getAttributes() const {
103 if (m_attributes.empty())
104 unmarshallAttributes();
107 const multimap<string,const Attribute*>& getIndexedAttributes() const {
108 if (m_attributeIndex.empty()) {
109 if (m_attributes.empty())
110 unmarshallAttributes();
111 for (vector<Attribute*>::const_iterator a = m_attributes.begin(); a != m_attributes.end(); ++a) {
112 const vector<string>& aliases = (*a)->getAliases();
113 for (vector<string>::const_iterator alias = aliases.begin(); alias != aliases.end(); ++alias)
114 m_attributeIndex.insert(multimap<string,const Attribute*>::value_type(*alias, *a));
117 return m_attributeIndex;
119 const vector<const char*>& getAssertionIDs() const {
121 DDF ids = m_obj["assertions"];
122 DDF id = ids.first();
123 while (id.isstring()) {
124 m_ids.push_back(id.string());
131 time_t expires() const { return m_expires; }
132 time_t lastAccess() const { return m_lastAccess; }
133 void validate(const Application& application, const char* client_addr, time_t* timeout);
136 void unmarshallAttributes() const;
140 mutable vector<Attribute*> m_attributes;
141 mutable multimap<string,const Attribute*> m_attributeIndex;
142 mutable vector<const char*> m_ids;
143 time_t m_expires,m_lastAccess;
144 RemotedCache* m_cache;
148 class RemotedCache : public SessionCache
151 RemotedCache(const DOMElement* e);
154 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
155 void remove(const char* key, const Application& application);
161 const DOMElement* m_root; // Only valid during initialization
163 map<string,RemotedSession*> m_hashtable;
165 void dormant(const char* key);
166 static void* cleanup_fn(void*);
168 CondWait* shutdown_wait;
169 Thread* cleanup_thread;
172 SessionCache* SHIBSP_DLLLOCAL RemotedCacheFactory(const DOMElement* const & e)
174 return new RemotedCache(e);
178 void RemotedSession::unmarshallAttributes() const
180 Attribute* attribute;
181 DDF attrs = m_obj["attributes"];
182 DDF attr = attrs.first();
183 while (!attr.isnull()) {
185 attribute = Attribute::unmarshall(attr);
186 m_attributes.push_back(attribute);
187 if (m_cache->m_log.isDebugEnabled())
188 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
189 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
191 catch (AttributeException& ex) {
192 const char* id = attr.first().name();
193 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
199 void RemotedSession::validate(const Application& application, const char* client_addr, time_t* timeout)
202 time_t now = time(NULL);
203 if (now > m_expires) {
204 m_cache->m_log.info("session expired (ID: %s)", getID());
205 throw opensaml::RetryableProfileException("Your session has expired, and you must re-authenticate.");
210 if (m_cache->m_log.isDebugEnabled())
211 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
212 if (strcmp(getClientAddress(),client_addr)) {
213 m_cache->m_log.warn("client address mismatch");
214 throw opensaml::RetryableProfileException(
215 "Your IP address ($1) does not match the address recorded at the time the session was established.",
216 params(1,client_addr)
224 DDF in("touch::"REMOTED_SESSION_CACHE"::SessionCache"), out;
227 in.addmember("key").string(getID());
228 in.addmember("version").integer(m_obj["version"].integer());
230 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
231 #ifndef HAVE_GMTIME_R
232 struct tm* ptime=gmtime(timeout);
235 struct tm* ptime=gmtime_r(timeout,&res);
238 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
239 in.addmember("timeout").string(timebuf);
243 out=application.getServiceProvider().getListenerService()->send(in);
250 if (out.isstruct()) {
251 // We got an updated record back.
253 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
254 m_attributes.clear();
255 m_attributeIndex.clear();
263 RemotedCache::RemotedCache(const DOMElement* e)
264 : SessionCache(e, 900), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_root(e), m_lock(NULL), shutdown(false)
266 if (!SPConfig::getConfig().getServiceProvider()->getListenerService())
267 throw ConfigurationException("RemotedCacheService requires a ListenerService, but none available.");
269 m_lock = RWLock::create();
270 shutdown_wait = CondWait::create();
271 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
274 RemotedCache::~RemotedCache()
276 // Shut down the cleanup thread and let it know...
278 shutdown_wait->signal();
279 cleanup_thread->join(NULL);
281 for_each(m_hashtable.begin(),m_hashtable.end(),xmltooling::cleanup_pair<string,RemotedSession>());
283 delete shutdown_wait;
286 Session* RemotedCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
289 xmltooling::NDC ndc("find");
292 RemotedSession* session=NULL;
293 m_log.debug("searching local cache for session (%s)", key);
295 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
296 if (i==m_hashtable.end()) {
298 m_log.debug("session not found locally, searching remote cache");
300 DDF in("find::"REMOTED_SESSION_CACHE"::SessionCache"), out;
303 in.addmember("key").string(key);
304 in.addmember("application_id").string(application.getId());
305 if (timeout && *timeout) {
306 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
307 #ifndef HAVE_GMTIME_R
308 struct tm* ptime=gmtime(timeout);
311 struct tm* ptime=gmtime_r(timeout,&res);
314 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
315 in.addmember("timeout").string(timebuf);
319 out=application.getServiceProvider().getListenerService()->send(in);
320 if (!out.isstruct()) {
322 m_log.debug("session not found in remote cache");
326 // Wrap the results in a local entry and save it.
327 session = new RemotedSession(this, out);
328 // The remote end has handled timeout issues, we handle address and expiration checks.
336 // Lock for writing and repeat the search to avoid duplication.
338 SharedLock shared(m_lock, false);
339 if (m_hashtable.count(key)) {
340 // We're using an existing session entry.
342 session = m_hashtable[key];
346 m_hashtable[key]=session;
351 // Save off and lock the session.
356 m_log.debug("session found locally, validating it for use");
359 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
360 m_log.error("an application (%s) tried to access another application's session", application.getId());
365 // Verify currency and update the timestamp if indicated by caller.
367 session->validate(application, client_addr, timeout);
371 remove(key, application);
378 void RemotedCache::remove(const char* key, const Application& application)
380 // Take care of local copy.
384 DDF in("remove::"REMOTED_SESSION_CACHE"::SessionCache");
387 in.addmember("key").string(key);
388 in.addmember("application_id").string(application.getId());
390 DDF out = application.getServiceProvider().getListenerService()->send(in);
394 void RemotedCache::dormant(const char* key)
397 xmltooling::NDC ndc("dormant");
400 m_log.debug("deleting local copy of session (%s)", key);
402 // lock the cache for writing, which means we know nobody is sitting in find()
405 // grab the entry from the table
406 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
407 if (i==m_hashtable.end()) {
412 // ok, remove the entry and lock it
413 RemotedSession* entry=i->second;
414 m_hashtable.erase(key);
420 // we can release the cache entry lock because we know we're not in the cache anymore
426 void RemotedCache::cleanup()
429 xmltooling::NDC ndc("cleanup");
432 Mutex* mutex = Mutex::create();
434 // Load our configuration details...
435 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
436 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
437 int rerun_timer = 900;
439 rerun_timer = XMLString::parseInt(tag);
440 if (rerun_timer <= 0)
445 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_cacheTimeout);
448 shutdown_wait->timedwait(mutex,rerun_timer);
452 // Ok, let's run through the cleanup process and clean out
453 // really old sessions. This is a two-pass process. The
454 // first pass is done holding a read-lock while we iterate over
455 // the cache. The second pass doesn't need a lock because
456 // the 'deletes' will lock the cache.
458 // Pass 1: iterate over the map and find all entries that have not been
460 vector<string> stale_keys;
461 time_t stale = time(NULL) - m_cacheTimeout;
463 m_log.debug("cleanup thread running");
466 for (map<string,RemotedSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
467 // If the last access was BEFORE the stale timeout...
469 time_t last=i->second->lastAccess();
472 stale_keys.push_back(i->first);
476 if (!stale_keys.empty()) {
477 m_log.info("purging %d old sessions", stale_keys.size());
479 // Pass 2: walk through the list of stale entries and remove them from the cache
480 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
484 m_log.debug("cleanup thread completed");
487 m_log.info("cleanup thread exiting");
494 void* RemotedCache::cleanup_fn(void* cache_p)
496 RemotedCache* cache = reinterpret_cast<RemotedCache*>(cache_p);
499 // First, let's block all signals
500 Thread::mask_all_signals();
503 // Now run the cleanup process.