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/shib-threads.h>
43 #include <shib-target/shib-target.h>
44 #include <log4cpp/Category.hh>
53 // wanted to use MySQL codes for this, but can't seem to get back a 145
54 #define isCorrupt(s) strstr(s,"(errno: 145)")
56 #ifdef HAVE_LIBDMALLOCXX
62 using namespace shibboleth;
63 using namespace shibtarget;
64 using namespace log4cpp;
66 #define PLUGIN_VER_MAJOR 3
67 #define PLUGIN_VER_MINOR 0
70 "CREATE TABLE state (" \
71 "cookie VARCHAR(64) PRIMARY KEY, " \
72 "application_id VARCHAR(255)," \
75 "addr VARCHAR(128)," \
78 "provider VARCHAR(256)," \
80 "authn_context TEXT," \
83 #define REPLAY_TABLE \
84 "CREATE TABLE replay (id VARCHAR(255) PRIMARY KEY, " \
85 "expires TIMESTAMP, " \
88 static const XMLCh Argument[] =
89 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
90 static const XMLCh cleanupInterval[] =
91 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
92 chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
94 static const XMLCh cacheTimeout[] =
95 { 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 };
96 static const XMLCh mysqlTimeout[] =
97 { 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 };
98 static const XMLCh storeAttributes[] =
99 { 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 };
101 static bool g_MySQLInitialized = false;
103 class MySQLBase : public virtual saml::IPlugIn
106 MySQLBase(const DOMElement* e);
107 virtual ~MySQLBase();
110 bool repairTable(MYSQL*&, const char* table);
112 log4cpp::Category* log;
116 const DOMElement* m_root; // can only use this during initialization
121 void createDatabase(MYSQL*, int major, int minor);
122 void upgradeDatabase(MYSQL*);
123 pair<int,int> getVersion(MYSQL*);
126 // Forward declarations
127 static void mysqlInit(const DOMElement* e, Category& log);
129 extern "C" void shib_mysql_destroy_handle(void* data)
131 MYSQL* mysql = (MYSQL*) data;
132 if (mysql) mysql_close(mysql);
135 MySQLBase::MySQLBase(const DOMElement* e) : m_root(e)
138 saml::NDC ndc("MySQLBase");
140 log = &(Category::getInstance("shibtarget.SessionCache.MySQL"));
142 m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
150 MySQLBase::~MySQLBase()
155 MYSQL* MySQLBase::getMYSQL()
158 saml::NDC ndc("getMYSQL");
161 // Do we already have a handle?
162 MYSQL* mysql=reinterpret_cast<MYSQL*>(m_mysql->getData());
166 // Connect to the database
167 mysql = mysql_init(NULL);
169 log->error("mysql_init failed");
171 throw SAMLException("MySQLBase::getMYSQL(): mysql_init() failed");
174 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shibd", 0, NULL, 0)) {
176 log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
178 throw SAMLException("MySQLBase::getMYSQL(): mysql_real_connect() failed");
181 log->info("mysql_real_connect failed: %s. Trying to create", mysql_error(mysql));
183 // This will throw an exception if it fails.
184 createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
188 pair<int,int> v=getVersion (mysql);
190 // Make sure we've got the right version
191 if (v.first != PLUGIN_VER_MAJOR || v.second != PLUGIN_VER_MINOR) {
193 // If we're capable, try upgrading on the fly...
194 if (v.first == 0 || v.first == 1 || v.first == 2) {
195 if (mysql_query(mysql, "DROP TABLE state")) {
196 log->error("error dropping old session state table: %s", mysql_error(mysql));
198 if (v.first==2 && mysql_query(mysql, "DROP TABLE replay")) {
199 log->error("error dropping old session state table: %s", mysql_error(mysql));
201 upgradeDatabase(mysql);
205 log->crit("Unknown database version: %d.%d", v.first, v.second);
206 throw SAMLException("MySQLBase::getMYSQL(): Unknown database version");
210 // We're all set.. Save off the handle for this thread.
211 m_mysql->setData(mysql);
215 bool MySQLBase::repairTable(MYSQL*& mysql, const char* table)
217 string q = string("REPAIR TABLE ") + table;
218 if (mysql_query(mysql, q.c_str())) {
219 log->error("Error repairing table %s: %s", table, mysql_error(mysql));
223 // seems we have to recycle the connection to get the thread to keep working
224 // other threads seem to be ok, but we should monitor that
226 m_mysql->setData(NULL);
231 void MySQLBase::createDatabase(MYSQL* mysql, int major, int minor)
233 log->info("creating database");
237 ms = mysql_init(NULL);
239 log->crit("mysql_init failed");
240 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_init failed");
243 if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
244 log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
245 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect failed");
248 if (mysql_query(ms, "CREATE DATABASE shibd")) {
249 log->crit("cannot create shibd database: %s", mysql_error(ms));
250 throw SAMLException("ShibMySQLCCache::createDatabase(): create db cmd failed");
253 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shibd", 0, NULL, 0)) {
254 log->crit("cannot open shibd database");
255 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect to plugin db failed");
261 catch (SAMLException&) {
268 // Now create the tables if they don't exist
269 log->info("Creating database tables");
271 if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)")) {
272 log->error ("error creating version: %s", mysql_error(mysql));
273 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
276 if (mysql_query(mysql,STATE_TABLE)) {
277 log->error ("error creating state table: %s", mysql_error(mysql));
278 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
281 if (mysql_query(mysql,REPLAY_TABLE)) {
282 log->error ("error creating replay table: %s", mysql_error(mysql));
283 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
287 q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
288 if (mysql_query(mysql, q.str().c_str())) {
289 log->error ("error setting version: %s", mysql_error(mysql));
290 throw SAMLException("ShibMySQLCCache::createDatabase(): version insert failed");
294 void MySQLBase::upgradeDatabase(MYSQL* mysql)
296 if (mysql_query(mysql,STATE_TABLE)) {
297 log->error ("error creating state table: %s", mysql_error(mysql));
298 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating state table");
301 if (mysql_query(mysql,REPLAY_TABLE)) {
302 log->error ("error creating replay table: %s", mysql_error(mysql));
303 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating replay table");
307 q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
308 if (mysql_query(mysql, q.str().c_str())) {
309 log->error ("error updating version: %s", mysql_error(mysql));
310 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error updating version");
314 pair<int,int> MySQLBase::getVersion(MYSQL* mysql)
316 // grab the version number from the database
317 if (mysql_query(mysql, "SELECT * FROM version")) {
318 log->error("error reading version: %s", mysql_error(mysql));
319 throw SAMLException("MySQLBase::getVersion(): error reading version");
322 MYSQL_RES* rows = mysql_store_result(mysql);
324 if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2) {
325 MYSQL_ROW row = mysql_fetch_row(rows);
326 int major = row[0] ? atoi(row[0]) : -1;
327 int minor = row[1] ? atoi(row[1]) : -1;
328 log->debug("opening database version %d.%d", major, minor);
329 mysql_free_result(rows);
330 return make_pair(major,minor);
333 // Wrong number of rows or wrong number of fields...
334 log->crit("Houston, we've got a problem with the database...");
335 mysql_free_result(rows);
336 throw SAMLException("MySQLBase::getVersion(): version verification failed");
339 log->crit("MySQL Read Failed in version verification");
340 throw SAMLException("MySQLBase::getVersion(): error reading version");
343 static void mysqlInit(const DOMElement* e, Category& log)
345 if (g_MySQLInitialized) {
346 log.info("MySQL embedded server already initialized");
349 log.info("initializing MySQL embedded server");
351 // Setup the argument array
352 vector<string> arg_array;
353 arg_array.push_back("shibboleth");
355 // grab any MySQL parameters from the config file
356 e=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
358 auto_ptr_char arg(e->getFirstChild()->getNodeValue());
360 arg_array.push_back(arg.get());
361 e=saml::XML::getNextSiblingElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
364 // Compute the argument array
365 vector<string>::size_type arg_count = arg_array.size();
366 const char** args=new const char*[arg_count];
367 for (vector<string>::size_type i = 0; i < arg_count; i++)
368 args[i] = arg_array[i].c_str();
370 // Initialize MySQL with the arguments
371 mysql_server_init(arg_count, (char **)args, NULL);
374 g_MySQLInitialized = true;
377 class ShibMySQLCCache : public MySQLBase, virtual public ISessionCache, virtual public ISessionCacheStore
380 ShibMySQLCCache(const DOMElement* e);
381 virtual ~ShibMySQLCCache();
383 // Delegate all the ISessionCache methods.
385 const IApplication* application,
386 const IEntityDescriptor* source,
387 const char* client_addr,
388 const SAMLSubject* subject,
389 const char* authnContext,
390 const SAMLResponse* tokens
392 { return m_cache->insert(application,source,client_addr,subject,authnContext,tokens); }
393 ISessionCacheEntry* find(const char* key, const IApplication* application, const char* client_addr)
394 { return m_cache->find(key,application,client_addr); }
395 void remove(const char* key, const IApplication* application, const char* client_addr)
396 { m_cache->remove(key,application,client_addr); }
398 bool setBackingStore(ISessionCacheStore*) {return false;}
400 // Store methods handle the database work
403 const IApplication* application,
404 const ISessionCacheEntry* entry,
411 string& applicationId,
412 string& clientAddress,
415 string& authnContext,
422 HRESULT onRead(const char* key, time_t& accessed);
423 HRESULT onRead(const char* key, string& tokens);
424 HRESULT onUpdate(const char* key, const char* tokens=NULL, time_t accessed=0);
425 HRESULT onDelete(const char* key);
430 bool m_storeAttributes;
431 ISessionCache* m_cache;
432 CondWait* shutdown_wait;
434 Thread* cleanup_thread;
436 static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
439 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e) : MySQLBase(e), m_storeAttributes(false)
442 saml::NDC ndc("ShibMySQLCCache");
445 m_cache = dynamic_cast<ISessionCache*>(
446 SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType, e)
448 if (!m_cache->setBackingStore(this)) {
450 throw SAMLException("Unable to register MySQL cache plugin as a cache store.");
453 shutdown_wait = CondWait::create();
456 // Load our configuration details...
457 const XMLCh* tag=m_root->getAttributeNS(NULL,storeAttributes);
458 if (tag && *tag && (*tag==chLatin_t || *tag==chDigit_1))
459 m_storeAttributes=true;
461 // Initialize the cleanup thread
462 cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
465 ShibMySQLCCache::~ShibMySQLCCache()
468 shutdown_wait->signal();
469 cleanup_thread->join(NULL);
473 HRESULT ShibMySQLCCache::onCreate(
475 const IApplication* application,
476 const ISessionCacheEntry* entry,
483 saml::NDC ndc("onCreate");
486 // Get XML data from entry. Default is not to return SAML objects.
487 const char* context=entry->getAuthnContext();
488 pair<const char*,const SAMLSubject*> subject=entry->getSubject();
489 pair<const char*,const SAMLResponse*> tokens=entry->getTokens();
492 q << "INSERT INTO state VALUES('" << key << "','" << application->getId() << "',";
494 q << "NOW(),NOW(),'";
496 q << "FROM_UNIXTIME(" << created << "),NOW(),'";
497 q << entry->getClientAddress() << "'," << majorVersion << "," << minorVersion << ",'" << entry->getProviderId() << "','"
498 << subject.first << "','" << context << "',";
500 if (m_storeAttributes && tokens.first)
501 q << "'" << tokens.first << "')";
505 if (log->isDebugEnabled())
506 log->debug("SQL insert: %s", q.str().c_str());
508 // then add it to the database
509 MYSQL* mysql = getMYSQL();
510 if (mysql_query(mysql, q.str().c_str())) {
511 const char* err=mysql_error(mysql);
512 log->error("error inserting %s: %s", key, err);
513 if (isCorrupt(err) && repairTable(mysql,"state")) {
515 if (mysql_query(mysql, q.str().c_str())) {
516 log->error("error inserting %s: %s", key, mysql_error(mysql));
527 HRESULT ShibMySQLCCache::onRead(
529 string& applicationId,
530 string& clientAddress,
533 string& authnContext,
542 saml::NDC ndc("onRead");
545 log->debug("searching MySQL database...");
547 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";
549 MYSQL* mysql = getMYSQL();
550 if (mysql_query(mysql, q.c_str())) {
551 const char* err=mysql_error(mysql);
552 log->error("error searching for %s: %s", key, err);
553 if (isCorrupt(err) && repairTable(mysql,"state")) {
554 if (mysql_query(mysql, q.c_str()))
555 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
559 MYSQL_RES* rows = mysql_store_result(mysql);
561 // Nope, doesn't exist.
562 if (!rows || mysql_num_rows(rows)==0) {
563 log->debug("not found in database");
565 mysql_free_result(rows);
569 // Make sure we got 1 and only 1 row.
570 if (mysql_num_rows(rows) > 1) {
571 log->error("database select returned %d rows!", mysql_num_rows(rows));
572 mysql_free_result(rows);
576 log->debug("session found, tranfering data back into memory");
591 MYSQL_ROW row = mysql_fetch_row(rows);
592 applicationId=row[0];
593 created=atoi(row[1]);
594 accessed=atoi(row[2]);
595 clientAddress=row[3];
596 majorVersion=atoi(row[4]);
597 minorVersion=atoi(row[5]);
605 mysql_free_result(rows);
610 HRESULT ShibMySQLCCache::onRead(const char* key, time_t& accessed)
613 saml::NDC ndc("onRead");
616 log->debug("reading last access time from MySQL database");
618 string q = string("SELECT UNIX_TIMESTAMP(atime) FROM state WHERE cookie='") + key + "' LIMIT 1";
620 MYSQL* mysql = getMYSQL();
621 if (mysql_query(mysql, q.c_str())) {
622 const char* err=mysql_error(mysql);
623 log->error("error searching for %s: %s", key, err);
624 if (isCorrupt(err) && repairTable(mysql,"state")) {
625 if (mysql_query(mysql, q.c_str()))
626 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
630 MYSQL_RES* rows = mysql_store_result(mysql);
632 // Nope, doesn't exist.
633 if (!rows || mysql_num_rows(rows)==0) {
634 log->warn("session expected, but not found in database");
636 mysql_free_result(rows);
640 // Make sure we got 1 and only 1 row.
641 if (mysql_num_rows(rows) != 1) {
642 log->error("database select returned %d rows!", mysql_num_rows(rows));
643 mysql_free_result(rows);
647 MYSQL_ROW row = mysql_fetch_row(rows);
648 accessed=atoi(row[0]);
651 mysql_free_result(rows);
656 HRESULT ShibMySQLCCache::onRead(const char* key, string& tokens)
659 saml::NDC ndc("onRead");
662 if (!m_storeAttributes)
665 log->debug("reading cached tokens from MySQL database");
667 string q = string("SELECT tokens FROM state WHERE cookie='") + key + "' LIMIT 1";
669 MYSQL* mysql = getMYSQL();
670 if (mysql_query(mysql, q.c_str())) {
671 const char* err=mysql_error(mysql);
672 log->error("error searching for %s: %s", key, err);
673 if (isCorrupt(err) && repairTable(mysql,"state")) {
674 if (mysql_query(mysql, q.c_str()))
675 log->error("error retrying search for %s: %s", key, mysql_error(mysql));
679 MYSQL_RES* rows = mysql_store_result(mysql);
681 // Nope, doesn't exist.
682 if (!rows || mysql_num_rows(rows)==0) {
683 log->warn("session expected, but not found in database");
685 mysql_free_result(rows);
689 // Make sure we got 1 and only 1 row.
690 if (mysql_num_rows(rows) != 1) {
691 log->error("database select returned %d rows!", mysql_num_rows(rows));
692 mysql_free_result(rows);
696 MYSQL_ROW row = mysql_fetch_row(rows);
701 mysql_free_result(rows);
706 HRESULT ShibMySQLCCache::onUpdate(const char* key, const char* tokens, time_t lastAccess)
709 saml::NDC ndc("onUpdate");
714 q << "UPDATE state SET atime=FROM_UNIXTIME(" << lastAccess << ")";
716 if (!m_storeAttributes)
718 q << "UPDATE state SET tokens=";
720 q << "'" << tokens << "'";
725 log->warn("onUpdate called with nothing to do!");
729 q << " WHERE cookie='" << key << "'";
731 MYSQL* mysql = getMYSQL();
732 if (mysql_query(mysql, q.str().c_str())) {
733 const char* err=mysql_error(mysql);
734 log->error("error updating %s: %s", key, err);
735 if (isCorrupt(err) && repairTable(mysql,"state")) {
737 if (mysql_query(mysql, q.str().c_str())) {
738 log->error("error updating %s: %s", key, mysql_error(mysql));
749 HRESULT ShibMySQLCCache::onDelete(const char* key)
752 saml::NDC ndc("onDelete");
755 // Remove from the database
756 string q = string("DELETE FROM state WHERE cookie='") + key + "'";
757 MYSQL* mysql = getMYSQL();
758 if (mysql_query(mysql, q.c_str())) {
759 const char* err=mysql_error(mysql);
760 log->error("error deleting entry %s: %s", key, err);
761 if (isCorrupt(err) && repairTable(mysql,"state")) {
763 if (mysql_query(mysql, q.c_str())) {
764 log->error("error deleting entry %s: %s", key, mysql_error(mysql));
775 void ShibMySQLCCache::cleanup()
778 saml::NDC ndc("cleanup");
781 Mutex* mutex = Mutex::create();
784 int timeout_life = 0;
786 // Load our configuration details...
787 const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
789 rerun_timer = XMLString::parseInt(tag);
791 // search for 'mysql-cache-timeout' and then the regular cache timeout
792 tag=m_root->getAttributeNS(NULL,mysqlTimeout);
794 timeout_life = XMLString::parseInt(tag);
796 tag=m_root->getAttributeNS(NULL,cacheTimeout);
798 timeout_life = XMLString::parseInt(tag);
801 if (rerun_timer <= 0)
802 rerun_timer = 300; // rerun every 5 minutes
804 if (timeout_life <= 0)
805 timeout_life = 28800; // timeout after 8 hours
809 MYSQL* mysql = getMYSQL();
811 log->info("cleanup thread started...Run every %d secs; timeout after %d secs", rerun_timer, timeout_life);
813 while (shutdown == false) {
814 shutdown_wait->timedwait(mutex, rerun_timer);
816 if (shutdown == true)
819 // Find all the entries in the database that haven't been used
820 // recently In particular, find all entries that have not been
821 // accessed in 'timeout_life' seconds.
823 q << "DELETE FROM state WHERE " << "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
825 if (mysql_query(mysql, q.str().c_str())) {
826 const char* err=mysql_error(mysql);
827 log->error("error purging old records: %s", err);
828 if (isCorrupt(err) && repairTable(mysql,"state")) {
829 if (mysql_query(mysql, q.str().c_str()))
830 log->error("error re-purging old records: %s", mysql_error(mysql));
835 log->info("cleanup thread exiting...");
842 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
844 ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
846 // First, let's block all signals
847 Thread::mask_all_signals();
849 // Now run the cleanup process.
854 class MySQLReplayCache : public MySQLBase, virtual public IReplayCache
857 MySQLReplayCache(const DOMElement* e);
858 virtual ~MySQLReplayCache() {}
860 bool check(const XMLCh* str, time_t expires) {auto_ptr_XMLCh temp(str); return check(temp.get(),expires);}
861 bool check(const char* str, time_t expires);
864 MySQLReplayCache::MySQLReplayCache(const DOMElement* e) : MySQLBase(e) {}
866 bool MySQLReplayCache::check(const char* str, time_t expires)
869 saml::NDC ndc("check");
872 // Remove expired entries
873 string q = string("DELETE FROM replay WHERE expires < NOW()");
874 MYSQL* mysql = getMYSQL();
875 if (mysql_query(mysql, q.c_str())) {
876 const char* err=mysql_error(mysql);
877 log->error("Error deleting expired entries: %s", err);
878 if (isCorrupt(err) && repairTable(mysql,"replay")) {
880 if (mysql_query(mysql, q.c_str()))
881 log->error("Error deleting expired entries: %s", mysql_error(mysql));
885 string q2 = string("SELECT id FROM replay WHERE id='") + str + "'";
886 if (mysql_query(mysql, q2.c_str())) {
887 const char* err=mysql_error(mysql);
888 log->error("Error searching for %s: %s", str, err);
889 if (isCorrupt(err) && repairTable(mysql,"replay")) {
890 if (mysql_query(mysql, q2.c_str())) {
891 log->error("Error retrying search for %s: %s", str, mysql_error(mysql));
892 throw SAMLException("Replay cache failed, please inform application support staff.");
896 throw SAMLException("Replay cache failed, please inform application support staff.");
900 MYSQL_RES* rows = mysql_store_result(mysql);
901 if (rows && mysql_num_rows(rows)>0) {
902 mysql_free_result(rows);
907 q3 << "INSERT INTO replay VALUES('" << str << "'," << "FROM_UNIXTIME(" << expires << "))";
909 // then add it to the database
910 if (mysql_query(mysql, q3.str().c_str())) {
911 const char* err=mysql_error(mysql);
912 log->error("Error inserting %s: %s", str, err);
913 if (isCorrupt(err) && repairTable(mysql,"state")) {
915 if (mysql_query(mysql, q3.str().c_str())) {
916 log->error("Error inserting %s: %s", str, mysql_error(mysql));
917 throw SAMLException("Replay cache failed, please inform application support staff.");
921 throw SAMLException("Replay cache failed, please inform application support staff.");
927 /*************************************************************************
928 * The registration functions here...
931 IPlugIn* new_mysql_ccache(const DOMElement* e)
933 return new ShibMySQLCCache(e);
936 IPlugIn* new_mysql_replay(const DOMElement* e)
938 return new MySQLReplayCache(e);
941 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
943 // register this ccache type
944 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::MySQLReplayCacheType, &new_mysql_replay);
945 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::MySQLSessionCacheType, &new_mysql_ccache);
949 extern "C" void SHIBMYSQL_EXPORTS saml_extension_term()
952 if (g_MySQLInitialized)
954 SAMLConfig::getConfig().getPlugMgr().unregFactory(shibtarget::XML::MySQLReplayCacheType);
955 SAMLConfig::getConfig().getPlugMgr().unregFactory(shibtarget::XML::MySQLSessionCacheType);