2 * shib-mysql-ccache.cpp: Shibboleth Credential Cache using MySQL.
4 * Created by: Derek Atkins <derek@ihtfp.com>
9 /* This file is loosely based off the Shibboleth Credential Cache.
10 * This plug-in is designed as a two-layer cache. Layer 1, the
11 * long-term cache, stores data in a MySQL embedded database. The
12 * data stored in layer 1 is only the session id (cookie), the
13 * "posted" SAML statement (expanded into an XML string), and usage
16 * Short-term data is cached in memory as SAML objects in the layer 2
17 * cache. Data like Attribute Authority assertions are stored in
21 // eventually we might be able to support autoconf via cygwin...
22 #if defined (_MSC_VER) || defined(__BORLANDC__)
23 # include "config_win32.h"
29 # define SHIBMYSQL_EXPORTS __declspec(dllexport)
31 # define SHIBMYSQL_EXPORTS
38 #include <shib-target/shib-target.h>
39 #include <shib-target/ccache-utils.h>
40 #include <shib/shib-threads.h>
41 #include <log4cpp/Category.hh>
48 #ifdef HAVE_LIBDMALLOCXX
54 using namespace shibboleth;
55 using namespace shibtarget;
57 class ShibMySQLCCache;
58 class ShibMySQLCCacheEntry : public CCacheEntry
61 ShibMySQLCCacheEntry(const char *, CCacheEntry*, ShibMySQLCCache*);
62 ~ShibMySQLCCacheEntry() {}
64 virtual Iterator<SAMLAssertion*> getAssertions(Resource& resource)
65 { return m_cacheEntry->getAssertions(resource); }
66 virtual void preFetch(Resource& resource, int prefetch_window)
67 { m_cacheEntry->preFetch(resource, prefetch_window); }
68 virtual bool isSessionValid(time_t lifetime, time_t timeout);
69 virtual const char* getClientAddress()
70 { return m_cacheEntry->getClientAddress(); }
71 virtual const char* getSerializedStatement()
72 { return m_cacheEntry->getSerializedStatement(); }
73 virtual const SAMLAuthenticationStatement* getStatement()
74 { return m_cacheEntry->getStatement(); }
75 virtual void release()
76 { m_cacheEntry->release(); delete this; }
81 ShibMySQLCCache* m_cache;
82 CCacheEntry *m_cacheEntry;
86 class ShibMySQLCCache : public CCache
90 virtual ~ShibMySQLCCache();
92 virtual SAMLBinding* getBinding(const XMLCh* bindingProt)
93 { return m_cache->getBinding(bindingProt); }
94 virtual CCacheEntry* find(const char* key);
95 virtual void insert(const char* key, SAMLAuthenticationStatement *s,
96 const char *client_addr);
97 virtual void remove(const char* key);
98 virtual void thread_init();
103 log4cpp::Category* log;
109 static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
110 CondWait* shutdown_wait;
112 Thread* cleanup_thread;
116 void createDatabase(MYSQL*, int major, int minor);
117 void getVersion(MYSQL*, int* major_p, int* minor_p);
118 void mysqlInit(void);
121 // Forward declarations
122 extern "C" void shib_mysql_destroy_handle(void* data);
124 /*************************************************************************
125 * The CCache here talks to a MySQL database. The database stores
126 * three items: the cookie (session key index), the lastAccess time, and
127 * the SAMLAuthenticationStatement. All other access is performed
128 * through the memory cache provided by shibboleth.
131 MYSQL* ShibMySQLCCache::getMYSQL()
133 void* data = m_mysql->getData();
137 void ShibMySQLCCache::thread_init()
139 saml::NDC ndc("open_db");
141 // Connect to the database
142 MYSQL* mysql = mysql_init(NULL);
144 log->error("mysql_init failed");
146 throw runtime_error("mysql_init()");
149 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
151 log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
152 throw runtime_error("mysql_real_connect");
155 log->info("mysql_real_connect failed: %s. Trying to create",
158 // This will throw a runtime error if it fails.
159 createDatabase(mysql, 0, 0);
163 int major = -1, minor = -1;
164 getVersion (mysql, &major, &minor);
166 // Make sure we've got the right version
167 if (major != 0 && minor != 0) {
168 log->crit("Invalid database version: %d.%d", major, minor);
169 throw runtime_error("Invalid Database version");
172 // We're all set.. Save off the handle for this thread.
173 m_mysql->setData((void*)mysql);
176 ShibMySQLCCache::ShibMySQLCCache()
178 saml::NDC ndc("shibmysql::ShibMySQLCCache");
180 m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
181 string ctx = "shibmysql::ShibMySQLCCache";
182 log = &(log4cpp::Category::getInstance(ctx));
189 m_cache = CCache::getInstance("memory");
191 // Initialize the cleanup thread
192 shutdown_wait = CondWait::create();
194 cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
197 ShibMySQLCCache::~ShibMySQLCCache()
200 shutdown_wait->signal();
201 cleanup_thread->join(NULL);
210 CCacheEntry* ShibMySQLCCache::find(const char* key)
212 saml::NDC ndc("mysql::find");
213 CCacheEntry* res = m_cache->find(key);
216 log->debug("Looking in database...");
218 // nothing cached; see if this exists in the database
220 q << "SELECT addr,statement FROM state WHERE cookie='" << key << "' LIMIT 1";
223 MYSQL* mysql = getMYSQL();
224 if (mysql_query(mysql, q.str().c_str()))
225 log->error("Error searching for %s: %s", key, mysql_error(mysql));
227 rows = mysql_store_result(mysql);
229 // Nope, doesn't exist.
233 // Make sure we got 1 and only 1 rows.
234 if (mysql_num_rows(rows) != 1) {
235 log->error("Select returned wrong number of rows: %d", mysql_num_rows(rows));
236 mysql_free_result(rows);
240 log->debug("Match found. Parsing...");
241 // Pull apart the row and process the results
242 MYSQL_ROW row = mysql_fetch_row(rows);
243 istringstream str(row[1]);
244 SAMLAuthenticationStatement *s = NULL;
246 // Try to parse the AuthStatement
248 s = new SAMLAuthenticationStatement(str);
250 mysql_free_result(rows);
254 // Insert it into the memory cache
256 m_cache->insert(key, s, row[0]);
258 // Free the results, and then re-run the 'find' query
259 mysql_free_result(rows);
260 res = m_cache->find(key);
265 return new ShibMySQLCCacheEntry(key, res, this);
268 void ShibMySQLCCache::insert(const char* key, SAMLAuthenticationStatement *s,
269 const char *client_addr)
271 saml::NDC ndc("mysql::insert");
276 q << "INSERT INTO state VALUES('" << key << "', NOW(), '" << client_addr
277 << "', '" << os.str() << "')";
279 log->debug("Query: %s", q.str().c_str());
281 // Add it to the memory cache
282 m_cache->insert(key, s, client_addr);
284 // then add it to the database
285 MYSQL* mysql = getMYSQL();
286 if (mysql_query(mysql, q.str().c_str()))
287 log->error("Error inserting %s: %s", key, mysql_error(mysql));
290 void ShibMySQLCCache::remove(const char* key)
292 saml::NDC ndc("mysql::remove");
294 // Remove the cached version
295 m_cache->remove(key);
297 // Remove from the database
299 q << "DELETE FROM state WHERE cookie='" << key << "'";
300 MYSQL* mysql = getMYSQL();
301 if (mysql_query(mysql, q.str().c_str()))
302 log->error("Error deleting entry %s: %s", key, mysql_error(mysql));
305 void ShibMySQLCCache::cleanup()
307 Mutex* mutex = Mutex::create();
308 saml::NDC ndc("mysql::cleanup()");
312 ShibTargetConfig& config = ShibTargetConfig::getConfig();
313 ShibINI& ini = config.getINI();
316 int timeout_life = 0;
319 if (ini.get_tag (SHIBTARGET_SHAR, SHIBTARGET_TAG_CACHECLEAN, true, &tag))
320 rerun_timer = atoi(tag.c_str());
322 // search for 'mysql-cache-timeout' and then the regular cache timeout
323 if (ini.get_tag (SHIBTARGET_SHAR, "mysql-cache-timeout", true, &tag))
324 timeout_life = atoi(tag.c_str());
325 else if (ini.get_tag (SHIBTARGET_SHAR, SHIBTARGET_TAG_CACHETIMEOUT, true, &tag))
326 timeout_life = atoi(tag.c_str());
328 if (rerun_timer <= 0)
329 rerun_timer = 300; // rerun every 5 minutes
331 if (timeout_life <= 0)
332 timeout_life = 28800; // timeout after 8 hours
336 MYSQL* mysql = getMYSQL();
338 while (shutdown == false) {
339 shutdown_wait->timedwait(mutex, rerun_timer);
341 if (shutdown == true)
344 // Find all the entries in the database that haven't been used
345 // recently In particular, find all entries that have not been
346 // accessed in 'timeout_life' seconds.
348 q << "SELECT cookie FROM state WHERE " <<
349 "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
352 if (mysql_query(mysql, q.str().c_str()))
353 log->error("Error searching for old items: %s", mysql_error(mysql));
355 rows = mysql_store_result(mysql);
359 if (mysql_num_fields(rows) != 1) {
360 log->error("Wrong number of rows, 1 != %d", mysql_num_fields(rows));
361 mysql_free_result(rows);
365 // For each row, remove the entry from the database.
367 while ((row = mysql_fetch_row(rows)) != NULL)
370 mysql_free_result(rows);
379 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
381 ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
383 // First, let's block all signals
384 Thread::mask_all_signals();
386 // Now run the cleanup process.
391 void ShibMySQLCCache::createDatabase(MYSQL* mysql, int major, int minor)
393 log->info("Creating database.");
397 ms = mysql_init(NULL);
399 log->crit("mysql_init failed");
400 throw new ShibTargetException();
403 if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
404 log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
405 throw new ShibTargetException();
408 if (mysql_query(ms, "CREATE DATABASE shar")) {
409 log->crit("cannot create shar database: %s", mysql_error(ms));
410 throw new ShibTargetException();
413 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
414 log->crit("cannot open SHAR database");
415 throw new ShibTargetException();
420 } catch (ShibTargetException&) {
424 throw runtime_error("mysql_real_connect");
427 // Now create the tables if they don't exist
428 log->info("Creating database tables.");
430 if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)"))
431 log->error ("Error creating version: %s", mysql_error(mysql));
433 if (mysql_query(mysql,
434 "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, "
435 "atime DATETIME, addr VARCHAR(128), statement TEXT)"))
436 log->error ("Error creating state: %s", mysql_error(mysql));
439 q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
440 if (mysql_query(mysql, q.str().c_str()))
441 log->error ("Error setting version: %s", mysql_error(mysql));
444 void ShibMySQLCCache::getVersion(MYSQL* mysql, int* major_p, int* minor_p)
446 // grab the version number from the database
447 if (mysql_query(mysql, "SELECT * FROM version"))
448 log->error ("Error reading version: %s", mysql_error(mysql));
450 MYSQL_RES* rows = mysql_store_result(mysql);
452 if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2) {
453 MYSQL_ROW row = mysql_fetch_row(rows);
455 int major = row[0] ? atoi(row[0]) : -1;
456 int minor = row[1] ? atoi(row[1]) : -1;
457 log->debug("opening database version %d.%d", major, minor);
459 mysql_free_result (rows);
466 // Wrong number of rows or wrong number of fields...
468 log->crit("Houston, we've got a problem with the database..");
469 mysql_free_result (rows);
470 throw runtime_error("Database version verification failed");
473 log->crit("MySQL Read Failed in version verificatoin");
474 throw runtime_error("MySQL Read Failed");
477 void ShibMySQLCCache::mysqlInit(void)
479 log->info ("Opening MySQL Database");
481 // Setup the argument array
482 vector<string> arg_array;
485 tag = SHIBTARGET_SHAR;
486 arg_array.push_back(tag);
488 // grab any MySQL parameters from the config file
489 ShibTargetConfig& config = ShibTargetConfig::getConfig();
490 ShibINI& ini = config.getINI();
492 if (ini.exists("mysql")) {
493 ShibINI::Iterator* iter = ini.tag_iterator("mysql");
495 for (const string* str = iter->begin(); str; str = iter->next()) {
496 string arg = ini.get("mysql", *str);
497 arg_array.push_back(arg);
502 // Compute the argument array
503 int arg_count = arg_array.size();
504 const char** args=new const char*[arg_count];
505 for (int i = 0; i < arg_count; i++)
506 args[i] = arg_array[i].c_str();
508 // Initialize MySQL with the arguments
509 mysql_server_init(arg_count, (char **)args, NULL);
514 /*************************************************************************
515 * The CCacheEntry here is mostly a wrapper around the "memory"
516 * cacheentry provided by shibboleth. The only difference is that we
517 * intercept the isSessionValid() so that we can "touch()" the
518 * database if the session is still valid.
521 ShibMySQLCCacheEntry::ShibMySQLCCacheEntry(const char* key, CCacheEntry *entry,
522 ShibMySQLCCache* cache)
524 m_cacheEntry = entry;
529 bool ShibMySQLCCacheEntry::isSessionValid(time_t lifetime, time_t timeout)
531 bool res = m_cacheEntry->isSessionValid(lifetime, timeout);
537 void ShibMySQLCCacheEntry::touch()
540 q << "UPDATE state SET atime=NOW() WHERE cookie='" << m_key << "'";
542 MYSQL* mysql = m_cache->getMYSQL();
543 if (mysql_query(mysql, q.str().c_str()))
544 m_cache->log->error("Error updating timestamp on %s: %s",
545 m_key.c_str(), mysql_error(mysql));
548 /*************************************************************************
549 * The registration functions here...
552 extern "C" CCache* new_mysql_ccache(void)
554 return new ShibMySQLCCache();
557 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void* context)
559 // register this ccache type
560 CCache::registerFactory("mysql", &new_mysql_ccache);
564 /*************************************************************************
568 extern "C" void shib_mysql_destroy_handle(void* data)
570 MYSQL* mysql = (MYSQL*) data;