2 * Copyright 2001-2005 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 * shib-mysql-ccache.cpp: Shibboleth Credential Cache using MySQL.
20 * Created by: Derek Atkins <derek@ihtfp.com>
25 // eventually we might be able to support autoconf via cygwin...
26 #if defined (_MSC_VER) || defined(__BORLANDC__)
27 # include "config_win32.h"
33 # define SHIBMYSQL_EXPORTS __declspec(dllexport)
35 # define SHIBMYSQL_EXPORTS
42 #include <shib-target/shib-target.h>
44 #include <log4cpp/Category.hh>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/Threads.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <shibsp/SPConfig.h>
49 using xmltooling::XMLHelper;
58 // wanted to use MySQL codes for this, but can't seem to get back a 145
59 #define isCorrupt(s) strstr(s,"(errno: 145)")
61 #ifdef HAVE_LIBDMALLOCXX
65 using namespace shibsp;
66 using namespace shibtarget;
67 using namespace opensaml::saml2md;
69 using namespace log4cpp;
72 #define PLUGIN_VER_MAJOR 3
73 #define PLUGIN_VER_MINOR 0
76 "CREATE TABLE state (" \
77 "cookie VARCHAR(64) PRIMARY KEY, " \
78 "application_id VARCHAR(255)," \
81 "addr VARCHAR(128)," \
84 "provider VARCHAR(256)," \
86 "authn_context TEXT," \
89 #define REPLAY_TABLE \
90 "CREATE TABLE replay (id VARCHAR(255) PRIMARY KEY, " \
91 "expires TIMESTAMP, " \
94 static const XMLCh Argument[] =
95 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
96 static const XMLCh cleanupInterval[] =
97 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
98 chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
100 static const XMLCh cacheTimeout[] =
101 { 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 };
102 static const XMLCh mysqlTimeout[] =
103 { 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 };
104 static const XMLCh storeAttributes[] =
105 { chLatin_s, chLatin_t, chLatin_o, chLatin_r, chLatin_e, chLatin_A, chLatin_t, chLatin_t, chLatin_r, chLatin_i, chLatin_b, chLatin_u, chLatin_t, chLatin_e, chLatin_s, chNull };
107 static bool g_MySQLInitialized = false;
109 class MySQLBase : public virtual saml::IPlugIn
112 MySQLBase(const DOMElement* e);
113 virtual ~MySQLBase();
116 bool repairTable(MYSQL*&, const char* table);
118 log4cpp::Category* log;
121 xmltooling::ThreadKey* m_mysql;
122 const DOMElement* m_root; // can only use this during initialization
127 void createDatabase(MYSQL*, int major, int minor);
128 void upgradeDatabase(MYSQL*);
129 pair<int,int> getVersion(MYSQL*);
132 // Forward declarations
133 static void mysqlInit(const DOMElement* e, Category& log);
135 extern "C" void shib_mysql_destroy_handle(void* data)
137 MYSQL* mysql = (MYSQL*) data;
138 if (mysql) mysql_close(mysql);
141 MySQLBase::MySQLBase(const DOMElement* e) : m_root(e)
144 xmltooling::NDC ndc("MySQLBase");
146 log = &(Category::getInstance("shibtarget.SessionCache.MySQL"));
148 m_mysql = xmltooling::ThreadKey::create(&shib_mysql_destroy_handle);
156 MySQLBase::~MySQLBase()
161 MYSQL* MySQLBase::getMYSQL()
164 xmltooling::NDC ndc("getMYSQL");
167 // Do we already have a handle?
168 MYSQL* mysql=reinterpret_cast<MYSQL*>(m_mysql->getData());
172 // Connect to the database
173 mysql = mysql_init(NULL);
175 log->error("mysql_init failed");
177 throw SAMLException("MySQLBase::getMYSQL(): mysql_init() failed");
180 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shibd", 0, NULL, 0)) {
182 log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
184 throw SAMLException("MySQLBase::getMYSQL(): mysql_real_connect() failed");
187 log->info("mysql_real_connect failed: %s. Trying to create", mysql_error(mysql));
189 // This will throw an exception if it fails.
190 createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
194 pair<int,int> v=getVersion (mysql);
196 // Make sure we've got the right version
197 if (v.first != PLUGIN_VER_MAJOR || v.second != PLUGIN_VER_MINOR) {
199 // If we're capable, try upgrading on the fly...
200 if (v.first == 0 || v.first == 1 || v.first == 2) {
201 if (mysql_query(mysql, "DROP TABLE state")) {
202 log->error("error dropping old session state table: %s", mysql_error(mysql));
204 if (v.first==2 && mysql_query(mysql, "DROP TABLE replay")) {
205 log->error("error dropping old session state table: %s", mysql_error(mysql));
207 upgradeDatabase(mysql);
211 log->crit("Unknown database version: %d.%d", v.first, v.second);
212 throw SAMLException("MySQLBase::getMYSQL(): Unknown database version");
216 // We're all set.. Save off the handle for this thread.
217 m_mysql->setData(mysql);
221 bool MySQLBase::repairTable(MYSQL*& mysql, const char* table)
223 string q = string("REPAIR TABLE ") + table;
224 if (mysql_query(mysql, q.c_str())) {
225 log->error("Error repairing table %s: %s", table, mysql_error(mysql));
229 // seems we have to recycle the connection to get the thread to keep working
230 // other threads seem to be ok, but we should monitor that
232 m_mysql->setData(NULL);
237 void MySQLBase::createDatabase(MYSQL* mysql, int major, int minor)
239 log->info("creating database");
243 ms = mysql_init(NULL);
245 log->crit("mysql_init failed");
246 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_init failed");
249 if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
250 log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
251 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect failed");
254 if (mysql_query(ms, "CREATE DATABASE shibd")) {
255 log->crit("cannot create shibd database: %s", mysql_error(ms));
256 throw SAMLException("ShibMySQLCCache::createDatabase(): create db cmd failed");
259 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shibd", 0, NULL, 0)) {
260 log->crit("cannot open shibd database");
261 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect to plugin db failed");
267 catch (SAMLException&) {
274 // Now create the tables if they don't exist
275 log->info("Creating database tables");
277 if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)")) {
278 log->error ("error creating version: %s", mysql_error(mysql));
279 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
282 if (mysql_query(mysql,STATE_TABLE)) {
283 log->error ("error creating state table: %s", mysql_error(mysql));
284 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
287 if (mysql_query(mysql,REPLAY_TABLE)) {
288 log->error ("error creating replay table: %s", mysql_error(mysql));
289 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
293 q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
294 if (mysql_query(mysql, q.str().c_str())) {
295 log->error ("error setting version: %s", mysql_error(mysql));
296 throw SAMLException("ShibMySQLCCache::createDatabase(): version insert failed");
300 void MySQLBase::upgradeDatabase(MYSQL* mysql)
302 if (mysql_query(mysql,STATE_TABLE)) {
303 log->error ("error creating state table: %s", mysql_error(mysql));
304 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating state table");
307 if (mysql_query(mysql,REPLAY_TABLE)) {
308 log->error ("error creating replay table: %s", mysql_error(mysql));
309 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating replay table");
313 q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
314 if (mysql_query(mysql, q.str().c_str())) {
315 log->error ("error updating version: %s", mysql_error(mysql));
316 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error updating version");
320 pair<int,int> MySQLBase::getVersion(MYSQL* mysql)
322 // grab the version number from the database
323 if (mysql_query(mysql, "SELECT * FROM version")) {
324 log->error("error reading version: %s", mysql_error(mysql));
325 throw SAMLException("MySQLBase::getVersion(): error reading version");
328 MYSQL_RES* rows = mysql_store_result(mysql);
330 if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2) {
331 MYSQL_ROW row = mysql_fetch_row(rows);
332 int major = row[0] ? atoi(row[0]) : -1;
333 int minor = row[1] ? atoi(row[1]) : -1;
334 log->debug("opening database version %d.%d", major, minor);
335 mysql_free_result(rows);
336 return make_pair(major,minor);
339 // Wrong number of rows or wrong number of fields...
340 log->crit("Houston, we've got a problem with the database...");
341 mysql_free_result(rows);
342 throw SAMLException("MySQLBase::getVersion(): version verification failed");
345 log->crit("MySQL Read Failed in version verification");
346 throw SAMLException("MySQLBase::getVersion(): error reading version");
349 static void mysqlInit(const DOMElement* e, Category& log)
351 if (g_MySQLInitialized) {
352 log.info("MySQL embedded server already initialized");
355 log.info("initializing MySQL embedded server");
357 // Setup the argument array
358 vector<string> arg_array;
359 arg_array.push_back("shibboleth");
361 // grab any MySQL parameters from the config file
362 e=XMLHelper::getFirstChildElement(e,Argument);
364 auto_ptr_char arg(e->getFirstChild()->getNodeValue());
366 arg_array.push_back(arg.get());
367 e=XMLHelper::getNextSiblingElement(e,Argument);
370 // Compute the argument array
371 vector<string>::size_type arg_count = arg_array.size();
372 const char** args=new const char*[arg_count];
373 for (vector<string>::size_type i = 0; i < arg_count; i++)
374 args[i] = arg_array[i].c_str();
376 // Initialize MySQL with the arguments
377 mysql_server_init(arg_count, (char **)args, NULL);
380 g_MySQLInitialized = true;
383 class ShibMySQLCCache : public MySQLBase, virtual public ISessionCache, virtual public ISessionCacheStore
386 ShibMySQLCCache(const DOMElement* e);
387 virtual ~ShibMySQLCCache();
389 // Delegate all the ISessionCache methods.
391 const IApplication* application,
392 const RoleDescriptor* role,
393 const char* client_addr,
394 const SAMLSubject* subject,
395 const char* authnContext,
396 const SAMLResponse* tokens
398 { return m_cache->insert(application,role,client_addr,subject,authnContext,tokens); }
399 ISessionCacheEntry* find(const char* key, const IApplication* application, const char* client_addr)
400 { return m_cache->find(key,application,client_addr); }
401 void remove(const char* key, const IApplication* application, const char* client_addr)
402 { m_cache->remove(key,application,client_addr); }
404 bool setBackingStore(ISessionCacheStore*) {return false;}
406 // Store methods handle the database work
409 const IApplication* application,
410 const ISessionCacheEntry* entry,
417 string& applicationId,
418 string& clientAddress,
421 string& authnContext,
428 HRESULT onRead(const char* key, time_t& accessed);
429 HRESULT onRead(const char* key, string& tokens);
430 HRESULT onUpdate(const char* key, const char* tokens=NULL, time_t accessed=0);
431 HRESULT onDelete(const char* key);
436 bool m_storeAttributes;
437 ISessionCache* m_cache;
438 xmltooling::CondWait* shutdown_wait;
440 xmltooling::Thread* cleanup_thread;
442 static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
445 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e) : MySQLBase(e), m_storeAttributes(false)
448 xmltooling::NDC ndc("ShibMySQLCCache");
451 m_cache = dynamic_cast<ISessionCache*>(
452 SAMLConfig::getConfig().getPlugMgr().newPlugin(MEMORY_SESSIONCACHE, e)
454 if (!m_cache->setBackingStore(this)) {
456 throw SAMLException("Unable to register MySQL cache plugin as a cache store.");
459 shutdown_wait = xmltooling::CondWait::create();
462 // Load our configuration details...
463 const XMLCh* tag=m_root->getAttributeNS(NULL,storeAttributes);
464 if (tag && *tag && (*tag==chLatin_t || *tag==chDigit_1))
465 m_storeAttributes=true;
467 // Initialize the cleanup thread
468 cleanup_thread = xmltooling::Thread::create(&cleanup_fcn, (void*)this);
471 ShibMySQLCCache::~ShibMySQLCCache()
474 shutdown_wait->signal();
475 cleanup_thread->join(NULL);
479 HRESULT ShibMySQLCCache::onCreate(
481 const IApplication* application,
482 const ISessionCacheEntry* entry,
489 xmltooling::NDC ndc("onCreate");
492 // Get XML data from entry. Default is not to return SAML objects.
493 const char* context=entry->getAuthnContext();
494 pair<const char*,const SAMLSubject*> subject=entry->getSubject();
495 pair<const char*,const SAMLResponse*> tokens=entry->getTokens();
498 q << "INSERT INTO state VALUES('" << key << "','" << application->getId() << "',";
500 q << "NOW(),NOW(),'";
502 q << "FROM_UNIXTIME(" << created << "),NOW(),'";
503 q << entry->getClientAddress() << "'," << majorVersion << "," << minorVersion << ",'" << entry->getProviderId() << "','"
504 << subject.first << "','" << context << "',";
506 if (m_storeAttributes && tokens.first)
507 q << "'" << tokens.first << "')";
511 if (log->isDebugEnabled())
512 log->debug("SQL insert: %s", q.str().c_str());
514 // then add it to the database
515 MYSQL* mysql = getMYSQL();
516 if (mysql_query(mysql, q.str().c_str())) {
517 const char* err=mysql_error(mysql);
518 log->error("error inserting %s: %s", key, err);
519 if (isCorrupt(err) && repairTable(mysql,"state")) {
521 if (mysql_query(mysql, q.str().c_str())) {
522 log->error("error inserting %s: %s", key, mysql_error(mysql));
533 HRESULT ShibMySQLCCache::onRead(
535 string& applicationId,
536 string& clientAddress,
539 string& authnContext,
548 xmltooling::NDC ndc("onRead");
551 log->debug("searching MySQL database...");
553 string q = string("SELECT application_id,UNIX_TIMESTAMP(ctime),UNIX_TIMESTAMP(atime),addr,major,minor,provider,subject,authn_context,tokens FROM state WHERE cookie='") + key + "' LIMIT 1";
555 MYSQL* mysql = getMYSQL();
556 if (mysql_query(mysql, q.c_str())) {
557 const char* err=mysql_error(mysql);
558 log->error("error searching for %s: %s", key, err);
559 if (isCorrupt(err) && repairTable(mysql,"state")) {
560 if (mysql_query(mysql, q.c_str()))
561 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
565 MYSQL_RES* rows = mysql_store_result(mysql);
567 // Nope, doesn't exist.
568 if (!rows || mysql_num_rows(rows)==0) {
569 log->debug("not found in database");
571 mysql_free_result(rows);
575 // Make sure we got 1 and only 1 row.
576 if (mysql_num_rows(rows) > 1) {
577 log->error("database select returned %d rows!", mysql_num_rows(rows));
578 mysql_free_result(rows);
582 log->debug("session found, tranfering data back into memory");
597 MYSQL_ROW row = mysql_fetch_row(rows);
598 applicationId=row[0];
599 created=atoi(row[1]);
600 accessed=atoi(row[2]);
601 clientAddress=row[3];
602 majorVersion=atoi(row[4]);
603 minorVersion=atoi(row[5]);
611 mysql_free_result(rows);
616 HRESULT ShibMySQLCCache::onRead(const char* key, time_t& accessed)
619 xmltooling::NDC ndc("onRead");
622 log->debug("reading last access time from MySQL database");
624 string q = string("SELECT UNIX_TIMESTAMP(atime) FROM state WHERE cookie='") + key + "' LIMIT 1";
626 MYSQL* mysql = getMYSQL();
627 if (mysql_query(mysql, q.c_str())) {
628 const char* err=mysql_error(mysql);
629 log->error("error searching for %s: %s", key, err);
630 if (isCorrupt(err) && repairTable(mysql,"state")) {
631 if (mysql_query(mysql, q.c_str()))
632 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
636 MYSQL_RES* rows = mysql_store_result(mysql);
638 // Nope, doesn't exist.
639 if (!rows || mysql_num_rows(rows)==0) {
640 log->warn("session expected, but not found in database");
642 mysql_free_result(rows);
646 // Make sure we got 1 and only 1 row.
647 if (mysql_num_rows(rows) != 1) {
648 log->error("database select returned %d rows!", mysql_num_rows(rows));
649 mysql_free_result(rows);
653 MYSQL_ROW row = mysql_fetch_row(rows);
654 accessed=atoi(row[0]);
657 mysql_free_result(rows);
662 HRESULT ShibMySQLCCache::onRead(const char* key, string& tokens)
665 xmltooling::NDC ndc("onRead");
668 if (!m_storeAttributes)
671 log->debug("reading cached tokens from MySQL database");
673 string q = string("SELECT tokens FROM state WHERE cookie='") + key + "' LIMIT 1";
675 MYSQL* mysql = getMYSQL();
676 if (mysql_query(mysql, q.c_str())) {
677 const char* err=mysql_error(mysql);
678 log->error("error searching for %s: %s", key, err);
679 if (isCorrupt(err) && repairTable(mysql,"state")) {
680 if (mysql_query(mysql, q.c_str()))
681 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
685 MYSQL_RES* rows = mysql_store_result(mysql);
687 // Nope, doesn't exist.
688 if (!rows || mysql_num_rows(rows)==0) {
689 log->warn("session expected, but not found in database");
691 mysql_free_result(rows);
695 // Make sure we got 1 and only 1 row.
696 if (mysql_num_rows(rows) != 1) {
697 log->error("database select returned %d rows!", mysql_num_rows(rows));
698 mysql_free_result(rows);
702 MYSQL_ROW row = mysql_fetch_row(rows);
707 mysql_free_result(rows);
712 HRESULT ShibMySQLCCache::onUpdate(const char* key, const char* tokens, time_t lastAccess)
715 xmltooling::NDC ndc("onUpdate");
720 q << "UPDATE state SET atime=FROM_UNIXTIME(" << lastAccess << ")";
722 if (!m_storeAttributes)
724 q << "UPDATE state SET tokens=";
726 q << "'" << tokens << "'";
731 log->warn("onUpdate called with nothing to do!");
735 q << " WHERE cookie='" << key << "'";
737 MYSQL* mysql = getMYSQL();
738 if (mysql_query(mysql, q.str().c_str())) {
739 const char* err=mysql_error(mysql);
740 log->error("error updating %s: %s", key, err);
741 if (isCorrupt(err) && repairTable(mysql,"state")) {
743 if (mysql_query(mysql, q.str().c_str())) {
744 log->error("error updating %s: %s", key, mysql_error(mysql));
755 HRESULT ShibMySQLCCache::onDelete(const char* key)
758 xmltooling::NDC ndc("onDelete");
761 // Remove from the database
762 string q = string("DELETE FROM state WHERE cookie='") + key + "'";
763 MYSQL* mysql = getMYSQL();
764 if (mysql_query(mysql, q.c_str())) {
765 const char* err=mysql_error(mysql);
766 log->error("error deleting entry %s: %s", key, err);
767 if (isCorrupt(err) && repairTable(mysql,"state")) {
769 if (mysql_query(mysql, q.c_str())) {
770 log->error("error deleting entry %s: %s", key, mysql_error(mysql));
781 void ShibMySQLCCache::cleanup()
784 xmltooling::NDC ndc("cleanup");
787 xmltooling::Mutex* mutex = xmltooling::Mutex::create();
790 int timeout_life = 0;
792 // Load our configuration details...
793 const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
795 rerun_timer = XMLString::parseInt(tag);
797 // search for 'mysql-cache-timeout' and then the regular cache timeout
798 tag=m_root->getAttributeNS(NULL,mysqlTimeout);
800 timeout_life = XMLString::parseInt(tag);
802 tag=m_root->getAttributeNS(NULL,cacheTimeout);
804 timeout_life = XMLString::parseInt(tag);
807 if (rerun_timer <= 0)
808 rerun_timer = 300; // rerun every 5 minutes
810 if (timeout_life <= 0)
811 timeout_life = 28800; // timeout after 8 hours
815 MYSQL* mysql = getMYSQL();
817 log->info("cleanup thread started...Run every %d secs; timeout after %d secs", rerun_timer, timeout_life);
819 while (shutdown == false) {
820 shutdown_wait->timedwait(mutex, rerun_timer);
822 if (shutdown == true)
825 // Find all the entries in the database that haven't been used
826 // recently In particular, find all entries that have not been
827 // accessed in 'timeout_life' seconds.
829 q << "DELETE FROM state WHERE " << "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
831 if (mysql_query(mysql, q.str().c_str())) {
832 const char* err=mysql_error(mysql);
833 log->error("error purging old records: %s", err);
834 if (isCorrupt(err) && repairTable(mysql,"state")) {
835 if (mysql_query(mysql, q.str().c_str()))
836 log->error("error re-purging old records: %s", mysql_error(mysql));
841 log->info("cleanup thread exiting...");
845 xmltooling::Thread::exit(NULL);
848 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
850 ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
853 // First, let'block all signals
854 xmltooling::Thread::mask_all_signals();
857 // Now run the cleanup process.
862 class MySQLReplayCache : public MySQLBase, virtual public IReplayCache
865 MySQLReplayCache(const DOMElement* e);
866 virtual ~MySQLReplayCache() {}
868 bool check(const XMLCh* str, time_t expires) {auto_ptr_XMLCh temp(str); return check(temp.get(),expires);}
869 bool check(const char* str, time_t expires);
872 MySQLReplayCache::MySQLReplayCache(const DOMElement* e) : MySQLBase(e) {}
874 bool MySQLReplayCache::check(const char* str, time_t expires)
877 xmltooling::NDC ndc("check");
880 // Remove expired entries
881 string q = string("DELETE FROM replay WHERE expires < NOW()");
882 MYSQL* mysql = getMYSQL();
883 if (mysql_query(mysql, q.c_str())) {
884 const char* err=mysql_error(mysql);
885 log->error("Error deleting expired entries: %s", err);
886 if (isCorrupt(err) && repairTable(mysql,"replay")) {
888 if (mysql_query(mysql, q.c_str()))
889 log->error("Error deleting expired entries: %s", mysql_error(mysql));
893 string q2 = string("SELECT id FROM replay WHERE id='") + str + "'";
894 if (mysql_query(mysql, q2.c_str())) {
895 const char* err=mysql_error(mysql);
896 log->error("Error searching for %s: %s", str, err);
897 if (isCorrupt(err) && repairTable(mysql,"replay")) {
898 if (mysql_query(mysql, q2.c_str())) {
899 log->error("Error retrying search for %s: %s", str, mysql_error(mysql));
900 throw SAMLException("Replay cache failed, please inform application support staff.");
904 throw SAMLException("Replay cache failed, please inform application support staff.");
908 MYSQL_RES* rows = mysql_store_result(mysql);
909 if (rows && mysql_num_rows(rows)>0) {
910 mysql_free_result(rows);
915 q3 << "INSERT INTO replay VALUES('" << str << "'," << "FROM_UNIXTIME(" << expires << "))";
917 // then add it to the database
918 if (mysql_query(mysql, q3.str().c_str())) {
919 const char* err=mysql_error(mysql);
920 log->error("Error inserting %s: %s", str, err);
921 if (isCorrupt(err) && repairTable(mysql,"state")) {
923 if (mysql_query(mysql, q3.str().c_str())) {
924 log->error("Error inserting %s: %s", str, mysql_error(mysql));
925 throw SAMLException("Replay cache failed, please inform application support staff.");
929 throw SAMLException("Replay cache failed, please inform application support staff.");
935 /*************************************************************************
936 * The registration functions here...
939 SessionCache* new_mysql_ccache(const DOMElement* const & e)
941 return new ShibMySQLCCache(e);
944 IPlugIn* new_mysql_replay(const DOMElement* e)
946 return new MySQLReplayCache(e);
949 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
951 // register this ccache type
952 SAMLConfig::getConfig().getPlugMgr().regFactory(MYSQL_REPLAYCACHE, &new_mysql_replay);
953 SPConfig::getConfig().SessionCacheManager.registerFactory(MYSQL_SESSIONCACHE, &new_mysql_ccache);
957 extern "C" void SHIBMYSQL_EXPORTS saml_extension_term()
960 if (g_MySQLInitialized)
962 SAMLConfig::getConfig().getPlugMgr().unregFactory(MYSQL_REPLAYCACHE);