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/shib-threads.h>
40 #include <log4cpp/Category.hh>
47 // wanted to use MySQL codes for this, but can't seem to get back a 145
48 #define isCorrupt(s) strstr(s,"(errno: 145)")
50 #ifdef HAVE_LIBDMALLOCXX
56 using namespace shibboleth;
57 using namespace shibtarget;
59 #define PLUGIN_VER_MAJOR 1
60 #define PLUGIN_VER_MINOR 0
62 static const XMLCh Argument[] =
63 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
64 static const XMLCh cleanupInterval[] =
65 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
66 chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
68 static const XMLCh cacheTimeout[] =
69 { chLatin_c, chLatin_a, chLatin_c, chLatin_h, chLatin_e, chLatin_T, chLatin_i, chLatin_m, chLatin_e, chLatin_o, chLatin_u, chLatin_t, chNull };
70 static const XMLCh mysqlTimeout[] =
71 { chLatin_m, chLatin_y, chLatin_s, chLatin_q, chLatin_l, chLatin_T, chLatin_i, chLatin_m, chLatin_e, chLatin_o, chLatin_u, chLatin_t, chNull };
73 class ShibMySQLCCache;
74 class ShibMySQLCCacheEntry : public ISessionCacheEntry
77 ShibMySQLCCacheEntry(const char*, ISessionCacheEntry*, ShibMySQLCCache*);
78 ~ShibMySQLCCacheEntry() {}
80 virtual void lock() {}
81 virtual void unlock() { m_cacheEntry->unlock(); delete this; }
82 virtual bool isValid(time_t lifetime, time_t timeout) const;
83 virtual const char* getClientAddress() const { return m_cacheEntry->getClientAddress(); }
84 virtual const SAMLAuthenticationStatement* getAuthnStatement() const { return m_cacheEntry->getAuthnStatement(); }
85 virtual Iterator<SAMLAssertion*> getAssertions() { return m_cacheEntry->getAssertions(); }
90 ShibMySQLCCache* m_cache;
91 ISessionCacheEntry* m_cacheEntry;
95 class ShibMySQLCCache : public ISessionCache
98 ShibMySQLCCache(const DOMElement* e);
99 virtual ~ShibMySQLCCache();
101 virtual void thread_init();
102 virtual void thread_end() {}
104 virtual string generateKey() const {return m_cache->generateKey();}
105 virtual ISessionCacheEntry* find(const char* key, const IApplication* application);
108 const IApplication* application,
109 SAMLAuthenticationStatement *s,
110 const char *client_addr,
111 SAMLResponse* r=NULL,
112 const IRoleDescriptor* source=NULL);
113 virtual void remove(const char* key);
116 MYSQL* getMYSQL() const;
118 log4cpp::Category* log;
121 ISessionCache* m_cache;
123 const DOMElement* m_root; // can only use this during initialization
125 static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
126 CondWait* shutdown_wait;
128 Thread* cleanup_thread;
132 void createDatabase(MYSQL*, int major, int minor);
133 void upgradeDatabase(MYSQL*);
134 void getVersion(MYSQL*, int* major_p, int* minor_p);
135 bool repairTable(MYSQL*&, const char* table);
136 void mysqlInit(void);
139 // Forward declarations
140 extern "C" void shib_mysql_destroy_handle(void* data);
142 /*************************************************************************
143 * The CCache here talks to a MySQL database. The database stores
144 * three items: the cookie (session key index), the lastAccess time, and
145 * the SAMLAuthenticationStatement. All other access is performed
146 * through the memory cache provided by shibboleth.
149 MYSQL* ShibMySQLCCache::getMYSQL() const
151 return (MYSQL*)m_mysql->getData();
154 void ShibMySQLCCache::thread_init()
156 saml::NDC ndc("thread_init");
158 // Connect to the database
159 MYSQL* mysql = mysql_init(NULL);
161 log->error("mysql_init failed");
163 throw SAMLException("ShibMySQLCCache::thread_init(): mysql_init() failed");
166 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
168 log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
170 throw SAMLException("ShibMySQLCCache::thread_init(): mysql_real_connect() failed");
172 log->info("mysql_real_connect failed: %s. Trying to create", mysql_error(mysql));
174 // This will throw an exception if it fails.
175 createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
179 int major = -1, minor = -1;
180 getVersion (mysql, &major, &minor);
182 // Make sure we've got the right version
183 if (major != PLUGIN_VER_MAJOR || minor != PLUGIN_VER_MINOR) {
185 // If we're capable, try upgrading on the fly...
186 if (major == 0 && minor == 0) {
187 upgradeDatabase(mysql);
191 log->crit("Invalid database version: %d.%d", major, minor);
192 throw SAMLException("ShibMySQLCCache::thread_init(): Invalid database version");
196 // We're all set.. Save off the handle for this thread.
197 m_mysql->setData(mysql);
200 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e)
202 saml::NDC ndc("shibmysql::ShibMySQLCCache");
204 m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
205 log = &(log4cpp::Category::getInstance("shibmysql::ShibMySQLCCache"));
213 m_cache = dynamic_cast<ISessionCache*>(
214 SAMLConfig::getConfig().getPlugMgr().newPlugin(
215 "edu.internet2.middleware.shibboleth.target.provider.MemorySessionCache", e
219 // Initialize the cleanup thread
220 shutdown_wait = CondWait::create();
222 cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
225 ShibMySQLCCache::~ShibMySQLCCache()
228 shutdown_wait->signal();
229 cleanup_thread->join(NULL);
239 ISessionCacheEntry* ShibMySQLCCache::find(const char* key, const IApplication* application)
241 saml::NDC ndc("ShibMySQLCCache::find");
242 ISessionCacheEntry* res = m_cache->find(key, application);
245 log->debug("Looking in database...");
247 // nothing cached; see if this exists in the database
248 string q = string("SELECT application_id,addr,statement FROM state WHERE cookie='") + key + "' LIMIT 1";
251 MYSQL* mysql = getMYSQL();
252 if (mysql_query(mysql, q.c_str())) {
253 const char* err=mysql_error(mysql);
254 log->error("Error searching for %s: %s", key, err);
255 if (isCorrupt(err) && repairTable(mysql,"state")) {
256 if (mysql_query(mysql, q.c_str()))
257 log->error("Error retrying search for %s: %s", key, mysql_error(mysql));
261 rows = mysql_store_result(mysql);
263 // Nope, doesn't exist.
267 // Make sure we got 1 and only 1 rows.
268 if (mysql_num_rows(rows) != 1) {
269 log->error("Select returned wrong number of rows: %d", mysql_num_rows(rows));
270 mysql_free_result(rows);
274 log->debug("Match found. Parsing...");
276 // Pull apart the row and process the results
277 MYSQL_ROW row = mysql_fetch_row(rows);
278 IConfig* conf=ShibTargetConfig::getConfig().getINI();
280 const IApplication* application=conf->getApplication(row[0]);
282 mysql_free_result(rows);
283 throw ShibTargetException(SHIBRPC_INTERNAL_ERROR,"unable to locate application for session, deleted?");
285 else if (strcmp(row[0],application->getId())) {
286 log->crit("An application (%s) attempted to access another application's (%s) session!", application->getId(), row[0]);
287 mysql_free_result(rows);
291 istringstream str(row[2]);
292 SAMLAuthenticationStatement *s = NULL;
294 // Try to parse the AuthStatement
296 s = new SAMLAuthenticationStatement(str);
298 mysql_free_result(rows);
302 // Insert it into the memory cache
304 m_cache->insert(key, application, s, row[1]);
306 // Free the results, and then re-run the 'find' query
307 mysql_free_result(rows);
308 res = m_cache->find(key,application);
313 return new ShibMySQLCCacheEntry(key, res, this);
316 void ShibMySQLCCache::insert(
318 const IApplication* application,
319 saml::SAMLAuthenticationStatement *s,
320 const char *client_addr,
321 saml::SAMLResponse* r,
322 const IRoleDescriptor* source)
324 saml::NDC ndc("ShibMySQLCCache::insert");
328 string q = string("INSERT INTO state VALUES('") + key + "','" + application->getId() + "',NOW(),'" + client_addr + "','" + os.str() + "')";
330 log->debug("Query: %s", q.c_str());
332 // then add it to the database
333 MYSQL* mysql = getMYSQL();
334 if (mysql_query(mysql, q.c_str())) {
335 const char* err=mysql_error(mysql);
336 log->error("Error inserting %s: %s", key, err);
337 if (isCorrupt(err) && repairTable(mysql,"state")) {
339 if (mysql_query(mysql, q.c_str()))
340 log->error("Error inserting %s: %s", key, mysql_error(mysql));
341 throw SAMLException("ShibMySQLCCache::insert(): inset failed");
345 // Add it to the memory cache
346 m_cache->insert(key, application, s, client_addr, r, source);
349 void ShibMySQLCCache::remove(const char* key)
351 saml::NDC ndc("ShibMySQLCCache::remove");
353 // Remove the cached version
354 m_cache->remove(key);
356 // Remove from the database
357 string q = string("DELETE FROM state WHERE cookie='") + key + "'";
358 MYSQL* mysql = getMYSQL();
359 if (mysql_query(mysql, q.c_str())) {
360 const char* err=mysql_error(mysql);
361 log->error("Error deleting entry %s: %s", key, err);
362 if (isCorrupt(err) && repairTable(mysql,"state")) {
364 if (mysql_query(mysql, q.c_str()))
365 log->error("Error deleting entry %s: %s", key, mysql_error(mysql));
370 void ShibMySQLCCache::cleanup()
372 Mutex* mutex = Mutex::create();
373 saml::NDC ndc("ShibMySQLCCache::cleanup");
378 int timeout_life = 0;
380 // Load our configuration details...
381 const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
383 rerun_timer = XMLString::parseInt(tag);
385 // search for 'mysql-cache-timeout' and then the regular cache timeout
386 tag=m_root->getAttributeNS(NULL,mysqlTimeout);
388 timeout_life = XMLString::parseInt(tag);
390 tag=m_root->getAttributeNS(NULL,cacheTimeout);
392 timeout_life = XMLString::parseInt(tag);
395 if (rerun_timer <= 0)
396 rerun_timer = 300; // rerun every 5 minutes
398 if (timeout_life <= 0)
399 timeout_life = 28800; // timeout after 8 hours
403 MYSQL* mysql = getMYSQL();
405 while (shutdown == false) {
406 shutdown_wait->timedwait(mutex, rerun_timer);
408 if (shutdown == true)
411 // Find all the entries in the database that haven't been used
412 // recently In particular, find all entries that have not been
413 // accessed in 'timeout_life' seconds.
415 q << "SELECT cookie FROM state WHERE " <<
416 "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
419 if (mysql_query(mysql, q.str().c_str())) {
420 const char* err=mysql_error(mysql);
421 log->error("Error searching for old items: %s", err);
422 if (isCorrupt(err) && repairTable(mysql,"state")) {
423 if (mysql_query(mysql, q.str().c_str()))
424 log->error("Error re-searching for old items: %s", mysql_error(mysql));
428 rows = mysql_store_result(mysql);
432 if (mysql_num_fields(rows) != 1) {
433 log->error("Wrong number of rows, 1 != %d", mysql_num_fields(rows));
434 mysql_free_result(rows);
438 // For each row, remove the entry from the database.
440 while ((row = mysql_fetch_row(rows)) != NULL)
443 mysql_free_result(rows);
446 log->debug("cleanup thread exiting...");
454 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
456 ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
458 // First, let's block all signals
459 Thread::mask_all_signals();
461 // Now run the cleanup process.
466 bool ShibMySQLCCache::repairTable(MYSQL*& mysql, const char* table)
468 string q = string("REPAIR TABLE ") + table;
469 if (mysql_query(mysql, q.c_str())) {
470 log->error("Error repairing table %s: %s", table, mysql_error(mysql));
474 // seems we have to recycle the connection to get the thread to keep working
475 // other threads seem to be ok, but we should monitor that
477 m_mysql->setData(NULL);
483 void ShibMySQLCCache::createDatabase(MYSQL* mysql, int major, int minor)
485 log->info("Creating database.");
489 ms = mysql_init(NULL);
491 log->crit("mysql_init failed");
492 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_init failed");
495 if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
496 log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
497 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect failed");
500 if (mysql_query(ms, "CREATE DATABASE shar")) {
501 log->crit("cannot create shar database: %s", mysql_error(ms));
502 throw SAMLException("ShibMySQLCCache::createDatabase(): create db cmd failed");
505 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
506 log->crit("cannot open SHAR database");
507 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect to shar db failed");
513 catch (SAMLException&) {
520 // Now create the tables if they don't exist
521 log->info("Creating database tables");
523 if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)")) {
524 log->error ("Error creating version: %s", mysql_error(mysql));
525 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
528 if (mysql_query(mysql,
529 "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, application_id VARCHAR(255),"
530 "atime DATETIME, addr VARCHAR(128), statement TEXT)")) {
531 log->error ("Error creating state: %s", mysql_error(mysql));
532 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
536 q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
537 if (mysql_query(mysql, q.str().c_str())) {
538 log->error ("Error setting version: %s", mysql_error(mysql));
539 throw SAMLException("ShibMySQLCCache::createDatabase(): version insert failed");
543 void ShibMySQLCCache::upgradeDatabase(MYSQL* mysql)
545 if (mysql_query(mysql, "DROP TABLE state")) {
546 log->error("Error dropping old session state table: %s", mysql_error(mysql));
549 if (mysql_query(mysql,
550 "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, application_id VARCHAR(255),"
551 "atime DATETIME, addr VARCHAR(128), statement TEXT)")) {
552 log->error ("Error creating state table: %s", mysql_error(mysql));
553 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating state table");
557 q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
558 if (mysql_query(mysql, q.str().c_str())) {
559 log->error ("Error updating version: %s", mysql_error(mysql));
560 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error updating version");
564 void ShibMySQLCCache::getVersion(MYSQL* mysql, int* major_p, int* minor_p)
566 // grab the version number from the database
567 if (mysql_query(mysql, "SELECT * FROM version"))
568 log->error ("Error reading version: %s", mysql_error(mysql));
570 MYSQL_RES* rows = mysql_store_result(mysql);
572 if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2) {
573 MYSQL_ROW row = mysql_fetch_row(rows);
575 int major = row[0] ? atoi(row[0]) : -1;
576 int minor = row[1] ? atoi(row[1]) : -1;
577 log->debug("opening database version %d.%d", major, minor);
579 mysql_free_result (rows);
586 // Wrong number of rows or wrong number of fields...
588 log->crit("Houston, we've got a problem with the database...");
589 mysql_free_result (rows);
590 throw SAMLException("ShibMySQLCCache::getVersion(): version verification failed");
593 log->crit("MySQL Read Failed in version verificatoin");
594 throw SAMLException("ShibMySQLCCache::getVersion(): error reading version");
597 void ShibMySQLCCache::mysqlInit(void)
599 log->info ("Opening MySQL Database");
601 // Setup the argument array
602 vector<string> arg_array;
603 arg_array.push_back("shar");
605 // grab any MySQL parameters from the config file
606 const DOMElement* e=saml::XML::getFirstChildElement(m_root,ShibTargetConfig::SHIBTARGET_NS,Argument);
608 auto_ptr_char arg(e->getFirstChild()->getNodeValue());
610 arg_array.push_back(arg.get());
611 e=saml::XML::getNextSiblingElement(e,ShibTargetConfig::SHIBTARGET_NS,Argument);
614 // Compute the argument array
615 int arg_count = arg_array.size();
616 const char** args=new const char*[arg_count];
617 for (int i = 0; i < arg_count; i++)
618 args[i] = arg_array[i].c_str();
620 // Initialize MySQL with the arguments
621 mysql_server_init(arg_count, (char **)args, NULL);
626 /*************************************************************************
627 * The CCacheEntry here is mostly a wrapper around the "memory"
628 * cacheentry provided by shibboleth. The only difference is that we
629 * intercept the isSessionValid() so that we can "touch()" the
630 * database if the session is still valid.
633 ShibMySQLCCacheEntry::ShibMySQLCCacheEntry(const char* key, ISessionCacheEntry* entry, ShibMySQLCCache* cache)
635 m_cacheEntry = entry;
640 bool ShibMySQLCCacheEntry::isValid(time_t lifetime, time_t timeout) const
642 bool res = m_cacheEntry->isValid(lifetime, timeout);
648 bool ShibMySQLCCacheEntry::touch() const
650 string q=string("UPDATE state SET atime=NOW() WHERE cookie='") + m_key + "'";
652 MYSQL* mysql = m_cache->getMYSQL();
653 if (mysql_query(mysql, q.c_str())) {
654 m_cache->log->info("Error updating timestamp on %s: %s",
655 m_key.c_str(), mysql_error(mysql));
661 /*************************************************************************
662 * The registration functions here...
665 IPlugIn* new_mysql_ccache(const DOMElement* e)
667 return new ShibMySQLCCache(e);
670 #define PLUGINTYPE "edu.internet2.middleware.shibboleth.target.provider.MySQLSessionCache"
672 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
674 // register this ccache type
675 SAMLConfig::getConfig().getPlugMgr().regFactory(PLUGINTYPE, &new_mysql_ccache);
679 extern "C" void SHIBMYSQL_EXPORTS saml_extension_term()
681 SAMLConfig::getConfig().getPlugMgr().unregFactory(PLUGINTYPE);
684 /*************************************************************************
688 extern "C" void shib_mysql_destroy_handle(void* data)
690 MYSQL* mysql = (MYSQL*) data;