2 * Copyright 2001-2007 Internet2
\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
8 * http://www.apache.org/licenses/LICENSE-2.0
\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
18 * RemotedSessionCache.cpp
\r
20 * SessionCache implementation that delegates to a remoted version.
\r
23 #include "internal.h"
\r
24 #include "Application.h"
\r
25 #include "exceptions.h"
\r
26 #include "ServiceProvider.h"
\r
27 #include "SessionCache.h"
\r
28 #include "attribute/Attribute.h"
\r
29 #include "remoting/ListenerService.h"
\r
30 #include "util/SPConstants.h"
\r
34 #include <log4cpp/Category.hh>
\r
35 #include <xmltooling/XMLToolingConfig.h>
\r
36 #include <xmltooling/util/DateTime.h>
\r
37 #include <xmltooling/util/NDC.h>
\r
38 #include <xmltooling/util/XMLHelper.h>
\r
40 using namespace shibsp;
\r
41 using namespace xmltooling;
\r
42 using namespace log4cpp;
\r
43 using namespace std;
\r
48 class RemotedSession : public virtual Session
\r
51 RemotedSession(RemotedCache* cache, DDF& obj) : m_version(obj["version"].integer()), m_obj(obj),
\r
52 m_expires(0), m_lastAccess(time(NULL)), m_cache(cache), m_lock(NULL) {
\r
53 auto_ptr_XMLCh exp(m_obj["expires"].string());
\r
55 DateTime iso(exp.get());
\r
56 iso.parseDateTime();
\r
57 m_expires = iso.getEpoch();
\r
60 m_lock = Mutex::create();
\r
66 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());
\r
77 const char* getID() const {
\r
78 return m_obj.name();
\r
80 const char* getApplicationID() const {
\r
81 return m_obj["application_id"].string();
\r
83 const char* getClientAddress() const {
\r
84 return m_obj["client_addr"].string();
\r
86 const char* getEntityID() const {
\r
87 return m_obj["entity_id"].string();
\r
89 const char* getProtocol() const {
\r
90 return m_obj["protocol"].string();
\r
92 const char* getAuthnInstant() const {
\r
93 return m_obj["authn_instant"].string();
\r
95 const char* getSessionIndex() const {
\r
96 return m_obj["session_index"].string();
\r
98 const char* getAuthnContextClassRef() const {
\r
99 return m_obj["authncontext_class"].string();
\r
101 const char* getAuthnContextDeclRef() const {
\r
102 return m_obj["authncontext_decl"].string();
\r
104 const multimap<string,Attribute*>& getAttributes() const {
\r
105 if (m_attributes.empty())
\r
106 unmarshallAttributes();
\r
107 return m_attributes;
\r
109 const vector<const char*>& getAssertionIDs() const {
\r
110 if (m_ids.empty()) {
\r
111 DDF ids = m_obj["assertions"];
\r
112 DDF id = ids.first();
\r
113 while (id.isstring()) {
\r
114 m_ids.push_back(id.string());
\r
121 time_t expires() const { return m_expires; }
\r
122 time_t lastAccess() const { return m_lastAccess; }
\r
123 void validate(const Application& application, const char* client_addr, time_t* timeout);
\r
126 void unmarshallAttributes() const;
\r
130 mutable multimap<string,Attribute*> m_attributes;
\r
131 mutable vector<const char*> m_ids;
\r
132 time_t m_expires,m_lastAccess;
\r
133 RemotedCache* m_cache;
\r
137 class RemotedCache : public SessionCache
\r
140 RemotedCache(const DOMElement* e);
\r
143 Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);
\r
144 void remove(const char* key, const Application& application);
\r
150 const DOMElement* m_root; // Only valid during initialization
\r
152 map<string,RemotedSession*> m_hashtable;
\r
154 void dormant(const char* key);
\r
155 static void* cleanup_fn(void*);
\r
157 CondWait* shutdown_wait;
\r
158 Thread* cleanup_thread;
\r
161 SessionCache* SHIBSP_DLLLOCAL RemotedCacheFactory(const DOMElement* const & e)
\r
163 return new RemotedCache(e);
\r
167 void RemotedSession::unmarshallAttributes() const
\r
169 Attribute* attribute;
\r
170 DDF attrs = m_obj["attributes"];
\r
171 DDF attr = attrs.first();
\r
172 while (!attr.isnull()) {
\r
174 attribute = Attribute::unmarshall(attr);
\r
175 m_attributes.insert(make_pair(attribute->getId(),attribute));
\r
176 if (m_cache->m_log.isDebugEnabled())
\r
177 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",
\r
178 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
\r
180 catch (AttributeException& ex) {
\r
181 const char* id = attr.first().name();
\r
182 m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
\r
184 attr = attrs.next();
\r
188 void RemotedSession::validate(const Application& application, const char* client_addr, time_t* timeout)
\r
190 // Basic expiration?
\r
191 time_t now = time(NULL);
\r
192 if (now > m_expires) {
\r
193 m_cache->m_log.info("session expired (ID: %s)", getID());
\r
194 throw opensaml::RetryableProfileException("Your session has expired, and you must re-authenticate.");
\r
199 if (m_cache->m_log.isDebugEnabled())
\r
200 m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());
\r
201 if (strcmp(getClientAddress(),client_addr)) {
\r
202 m_cache->m_log.warn("client address mismatch");
\r
203 throw opensaml::RetryableProfileException(
\r
204 "Your IP address ($1) does not match the address recorded at the time the session was established.",
\r
205 params(1,client_addr)
\r
213 DDF in("touch::"REMOTED_SESSION_CACHE"::SessionCache"), out;
\r
214 DDFJanitor jin(in);
\r
216 in.addmember("key").string(getID());
\r
217 in.addmember("version").integer(m_obj["version"].integer());
\r
219 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
220 #ifndef HAVE_GMTIME_R
\r
221 struct tm* ptime=gmtime(timeout);
\r
224 struct tm* ptime=gmtime_r(timeout,&res);
\r
227 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
228 in.addmember("timeout").string(timebuf);
\r
232 out=application.getServiceProvider().getListenerService()->send(in);
\r
239 if (out.isstruct()) {
\r
240 // We got an updated record back.
\r
242 for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());
\r
243 m_attributes.clear();
\r
248 m_lastAccess = now;
\r
251 RemotedCache::RemotedCache(const DOMElement* e)
\r
252 : SessionCache(e), m_log(Category::getInstance(SHIBSP_LOGCAT".SessionCache")), m_root(e), m_lock(NULL), shutdown(false)
\r
254 if (!SPConfig::getConfig().getServiceProvider()->getListenerService())
\r
255 throw ConfigurationException("RemotedCacheService requires a ListenerService, but none available.");
\r
257 m_lock = RWLock::create();
\r
258 shutdown_wait = CondWait::create();
\r
259 cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
\r
262 RemotedCache::~RemotedCache()
\r
264 // Shut down the cleanup thread and let it know...
\r
266 shutdown_wait->signal();
\r
267 cleanup_thread->join(NULL);
\r
269 for_each(m_hashtable.begin(),m_hashtable.end(),xmltooling::cleanup_pair<string,RemotedSession>());
\r
271 delete shutdown_wait;
\r
274 Session* RemotedCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)
\r
277 xmltooling::NDC ndc("find");
\r
280 RemotedSession* session=NULL;
\r
281 m_log.debug("searching local cache for session (%s)", key);
\r
283 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
\r
284 if (i==m_hashtable.end()) {
\r
286 m_log.debug("session not found locally, searching remote cache");
\r
288 DDF in("find::"REMOTED_SESSION_CACHE"::SessionCache"), out;
\r
289 DDFJanitor jin(in);
\r
291 in.addmember("key").string(key);
\r
292 in.addmember("application_id").string(application.getId());
\r
293 if (timeout && *timeout) {
\r
294 // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.
\r
295 #ifndef HAVE_GMTIME_R
\r
296 struct tm* ptime=gmtime(timeout);
\r
299 struct tm* ptime=gmtime_r(timeout,&res);
\r
302 strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
\r
303 in.addmember("timeout").string(timebuf);
\r
307 out=application.getServiceProvider().getListenerService()->send(in);
\r
308 if (!out.isstruct()) {
\r
310 m_log.debug("session not found in remote cache");
\r
314 // Wrap the results in a local entry and save it.
\r
315 session = new RemotedSession(this, out);
\r
316 // The remote end has handled timeout issues, we handle address and expiration checks.
\r
324 // Lock for writing and repeat the search to avoid duplication.
\r
326 SharedLock shared(m_lock, false);
\r
327 if (m_hashtable.count(key)) {
\r
328 // We're using an existing session entry.
\r
330 session = m_hashtable[key];
\r
334 m_hashtable[key]=session;
\r
339 // Save off and lock the session.
\r
340 session = i->second;
\r
344 m_log.debug("session found locally, validating it for use");
\r
347 if (!XMLString::equals(session->getApplicationID(), application.getId())) {
\r
348 m_log.error("an application (%s) tried to access another application's session", application.getId());
\r
353 // Verify currency and update the timestamp if indicated by caller.
\r
355 session->validate(application, client_addr, timeout);
\r
359 remove(key, application);
\r
366 void RemotedCache::remove(const char* key, const Application& application)
\r
368 // Take care of local copy.
\r
372 DDF in("remove::"REMOTED_SESSION_CACHE"::SessionCache");
\r
373 DDFJanitor jin(in);
\r
375 in.addmember("key").string(key);
\r
376 in.addmember("application_id").string(application.getId());
\r
378 DDF out = application.getServiceProvider().getListenerService()->send(in);
\r
382 void RemotedCache::dormant(const char* key)
\r
385 xmltooling::NDC ndc("dormant");
\r
388 m_log.debug("deleting local copy of session (%s)", key);
\r
390 // lock the cache for writing, which means we know nobody is sitting in find()
\r
393 // grab the entry from the table
\r
394 map<string,RemotedSession*>::const_iterator i=m_hashtable.find(key);
\r
395 if (i==m_hashtable.end()) {
\r
400 // ok, remove the entry and lock it
\r
401 RemotedSession* entry=i->second;
\r
402 m_hashtable.erase(key);
\r
405 // unlock the cache
\r
408 // we can release the cache entry lock because we know we're not in the cache anymore
\r
414 void RemotedCache::cleanup()
\r
417 xmltooling::NDC ndc("cleanup");
\r
420 Mutex* mutex = Mutex::create();
\r
422 // Load our configuration details...
\r
423 static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
\r
424 const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;
\r
425 int rerun_timer = 900;
\r
427 rerun_timer = XMLString::parseInt(tag);
\r
428 if (rerun_timer <= 0)
\r
433 m_log.info("cleanup thread started...run every %d secs; timeout after %d secs", rerun_timer, m_cacheTimeout);
\r
435 while (!shutdown) {
\r
436 shutdown_wait->timedwait(mutex,rerun_timer);
\r
440 // Ok, let's run through the cleanup process and clean out
\r
441 // really old sessions. This is a two-pass process. The
\r
442 // first pass is done holding a read-lock while we iterate over
\r
443 // the cache. The second pass doesn't need a lock because
\r
444 // the 'deletes' will lock the cache.
\r
446 // Pass 1: iterate over the map and find all entries that have not been
\r
448 vector<string> stale_keys;
\r
449 time_t stale = time(NULL) - m_cacheTimeout;
\r
452 for (map<string,RemotedSession*>::const_iterator i=m_hashtable.begin(); i!=m_hashtable.end(); ++i) {
\r
453 // If the last access was BEFORE the stale timeout...
\r
455 time_t last=i->second->lastAccess();
\r
456 i->second->unlock();
\r
458 stale_keys.push_back(i->first);
\r
462 if (!stale_keys.empty()) {
\r
463 m_log.info("purging %d old sessions", stale_keys.size());
\r
465 // Pass 2: walk through the list of stale entries and remove them from the cache
\r
466 for (vector<string>::const_iterator j = stale_keys.begin(); j != stale_keys.end(); ++j)
\r
467 dormant(j->c_str());
\r
471 m_log.info("cleanup thread exiting");
\r
475 Thread::exit(NULL);
\r
478 void* RemotedCache::cleanup_fn(void* cache_p)
\r
480 RemotedCache* cache = reinterpret_cast<RemotedCache*>(cache_p);
\r
483 // First, let's block all signals
\r
484 Thread::mask_all_signals();
\r
487 // Now run the cleanup process.
\r