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 /* This file is loosely based off the Shibboleth Credential Cache.
26 * This plug-in is designed as a two-layer cache. Layer 1, the
27 * long-term cache, stores data in a MySQL embedded database.
29 * Short-term data is cached in memory as SAML objects in the layer 2
33 // eventually we might be able to support autoconf via cygwin...
34 #if defined (_MSC_VER) || defined(__BORLANDC__)
35 # include "config_win32.h"
41 # define SHIBMYSQL_EXPORTS __declspec(dllexport)
43 # define SHIBMYSQL_EXPORTS
50 #include <shib-target/shib-target.h>
51 #include <shib/shib-threads.h>
53 #if defined(HAVE_LOG4SHIB)
54 # include <log4shib/Category.hh>
56 namespace logging = log4shib;
58 #elif defined(HAVE_LOG4CPP)
59 # include <log4cpp/Category.hh>
61 namespace logging = log4cpp;
64 # error "Supported logging library not available."
72 // wanted to use MySQL codes for this, but can't seem to get back a 145
73 #define isCorrupt(s) strstr(s,"(errno: 145)")
75 #ifdef HAVE_LIBDMALLOCXX
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace shibmysql::logging;
85 #define PLUGIN_VER_MAJOR 2
86 #define PLUGIN_VER_MINOR 0
89 "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, " \
90 "application_id VARCHAR(255)," \
93 "addr VARCHAR(128)," \
95 "provider VARCHAR(256)," \
96 "response_id VARCHAR(128)," \
100 #define REPLAY_TABLE \
101 "CREATE TABLE replay (id VARCHAR(255) PRIMARY KEY, " \
102 "expires TIMESTAMP, " \
105 static const XMLCh Argument[] =
106 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
107 static const XMLCh cleanupInterval[] =
108 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
109 chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
111 static const XMLCh cacheTimeout[] =
112 { 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 };
113 static const XMLCh mysqlTimeout[] =
114 { 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 };
115 static const XMLCh storeAttributes[] =
116 { 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 };
121 MySQLBase(const DOMElement* e);
122 virtual ~MySQLBase();
127 MYSQL* getMYSQL() const;
128 bool repairTable(MYSQL*&, const char* table);
134 const DOMElement* m_root; // can only use this during initialization
138 void createDatabase(MYSQL*, int major, int minor);
139 void upgradeDatabase(MYSQL*);
140 void getVersion(MYSQL*, int* major_p, int* minor_p);
143 // Forward declarations
144 static void mysqlInit(const DOMElement* e, Category& log);
146 extern "C" void shib_mysql_destroy_handle(void* data)
148 MYSQL* mysql = (MYSQL*) data;
149 if (mysql) mysql_close(mysql);
152 MySQLBase::MySQLBase(const DOMElement* e) : m_root(e)
155 saml::NDC ndc("MySQLBase");
157 log = &(Category::getInstance("shibmysql.MySQLBase"));
159 m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
167 MySQLBase::~MySQLBase()
174 MYSQL* MySQLBase::getMYSQL() const
176 return (MYSQL*)m_mysql->getData();
179 void MySQLBase::thread_init()
182 saml::NDC ndc("thread_init");
185 // Connect to the database
186 MYSQL* mysql = mysql_init(NULL);
188 log->error("mysql_init failed");
190 throw SAMLException("MySQLBase::thread_init(): mysql_init() failed");
193 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
195 log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
197 throw SAMLException("MySQLBase::thread_init(): mysql_real_connect() failed");
199 log->info("mysql_real_connect failed: %s. Trying to create", mysql_error(mysql));
201 // This will throw an exception if it fails.
202 createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
206 int major = -1, minor = -1;
207 getVersion (mysql, &major, &minor);
209 // Make sure we've got the right version
210 if (major != PLUGIN_VER_MAJOR || minor != PLUGIN_VER_MINOR) {
212 // If we're capable, try upgrading on the fly...
213 if (major == 0 || major == 1) {
214 upgradeDatabase(mysql);
218 log->crit("Unknown database version: %d.%d", major, minor);
219 throw SAMLException("MySQLBase::thread_init(): Unknown database version");
223 // We're all set.. Save off the handle for this thread.
224 m_mysql->setData(mysql);
227 bool MySQLBase::repairTable(MYSQL*& mysql, const char* table)
229 string q = string("REPAIR TABLE ") + table;
230 if (mysql_query(mysql, q.c_str())) {
231 log->error("Error repairing table %s: %s", table, mysql_error(mysql));
235 // seems we have to recycle the connection to get the thread to keep working
236 // other threads seem to be ok, but we should monitor that
238 m_mysql->setData(NULL);
244 void MySQLBase::createDatabase(MYSQL* mysql, int major, int minor)
246 log->info("Creating database.");
250 ms = mysql_init(NULL);
252 log->crit("mysql_init failed");
253 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_init failed");
256 if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
257 log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
258 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect failed");
261 if (mysql_query(ms, "CREATE DATABASE shar")) {
262 log->crit("cannot create shar database: %s", mysql_error(ms));
263 throw SAMLException("ShibMySQLCCache::createDatabase(): create db cmd failed");
266 if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
267 log->crit("cannot open SHAR database");
268 throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect to plugin db failed");
274 catch (SAMLException&) {
281 // Now create the tables if they don't exist
282 log->info("Creating database tables");
284 if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)")) {
285 log->error ("Error creating version: %s", mysql_error(mysql));
286 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
289 if (mysql_query(mysql,STATE_TABLE)) {
290 log->error ("Error creating state table: %s", mysql_error(mysql));
291 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
294 if (mysql_query(mysql,REPLAY_TABLE)) {
295 log->error ("Error creating replay table: %s", mysql_error(mysql));
296 throw SAMLException("ShibMySQLCCache::createDatabase(): create table cmd failed");
300 q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
301 if (mysql_query(mysql, q.str().c_str())) {
302 log->error ("Error setting version: %s", mysql_error(mysql));
303 throw SAMLException("ShibMySQLCCache::createDatabase(): version insert failed");
307 void MySQLBase::upgradeDatabase(MYSQL* mysql)
309 if (mysql_query(mysql, "DROP TABLE state")) {
310 log->error("Error dropping old session state table: %s", mysql_error(mysql));
313 if (mysql_query(mysql,STATE_TABLE)) {
314 log->error ("Error creating state table: %s", mysql_error(mysql));
315 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating state table");
318 if (mysql_query(mysql,REPLAY_TABLE)) {
319 log->error ("Error creating replay table: %s", mysql_error(mysql));
320 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating replay table");
324 q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
325 if (mysql_query(mysql, q.str().c_str())) {
326 log->error ("Error updating version: %s", mysql_error(mysql));
327 throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error updating version");
331 void MySQLBase::getVersion(MYSQL* mysql, int* major_p, int* minor_p)
333 // grab the version number from the database
334 if (mysql_query(mysql, "SELECT * FROM version"))
335 log->error ("Error reading version: %s", mysql_error(mysql));
337 MYSQL_RES* rows = mysql_store_result(mysql);
339 if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2) {
340 MYSQL_ROW row = mysql_fetch_row(rows);
342 int major = row[0] ? atoi(row[0]) : -1;
343 int minor = row[1] ? atoi(row[1]) : -1;
344 log->debug("opening database version %d.%d", major, minor);
346 mysql_free_result (rows);
353 // Wrong number of rows or wrong number of fields...
355 log->crit("Houston, we've got a problem with the database...");
356 mysql_free_result (rows);
357 throw SAMLException("ShibMySQLCCache::getVersion(): version verification failed");
360 log->crit("MySQL Read Failed in version verificatoin");
361 throw SAMLException("ShibMySQLCCache::getVersion(): error reading version");
364 static void mysqlInit(const DOMElement* e, Category& log)
366 static bool done = false;
368 log.info("MySQL embedded server already initialized");
371 log.info("initializing MySQL embedded server");
373 // Setup the argument array
374 vector<string> arg_array;
375 arg_array.push_back("shibboleth");
377 // grab any MySQL parameters from the config file
378 e=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
380 auto_ptr_char arg(e->getFirstChild()->getNodeValue());
382 arg_array.push_back(arg.get());
383 e=saml::XML::getNextSiblingElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
386 // Compute the argument array
387 int arg_count = arg_array.size();
388 const char** args=new const char*[arg_count];
389 for (int i = 0; i < arg_count; i++)
390 args[i] = arg_array[i].c_str();
392 // Initialize MySQL with the arguments
393 mysql_server_init(arg_count, (char **)args, NULL);
399 class ShibMySQLCCache;
400 class ShibMySQLCCacheEntry : public ISessionCacheEntry
403 ShibMySQLCCacheEntry(const char* key, ISessionCacheEntry* entry, ShibMySQLCCache* cache)
404 : m_cacheEntry(entry), m_key(key), m_cache(cache), m_responseId(NULL) {}
405 ~ShibMySQLCCacheEntry() {if (m_responseId) XMLString::release(&m_responseId);}
407 virtual void lock() {}
408 virtual void unlock() { m_cacheEntry->unlock(); delete this; }
409 virtual bool isValid(time_t lifetime, time_t timeout) const;
410 virtual const char* getClientAddress() const { return m_cacheEntry->getClientAddress(); }
411 virtual ShibProfile getProfile() const { return m_cacheEntry->getProfile(); }
412 virtual const char* getProviderId() const { return m_cacheEntry->getProviderId(); }
413 virtual const SAMLAuthenticationStatement* getAuthnStatement() const { return m_cacheEntry->getAuthnStatement(); }
414 virtual CachedResponse getResponse();
419 ShibMySQLCCache* m_cache;
420 ISessionCacheEntry* m_cacheEntry;
425 class ShibMySQLCCache : public MySQLBase, virtual public ISessionCache
428 ShibMySQLCCache(const DOMElement* e);
429 virtual ~ShibMySQLCCache();
431 virtual void thread_init() {MySQLBase::thread_init();}
432 virtual void thread_end() {MySQLBase::thread_end();}
434 virtual string generateKey() const {return m_cache->generateKey();}
435 virtual ISessionCacheEntry* find(const char* key, const IApplication* application);
438 const IApplication* application,
439 const char* client_addr,
441 const char* providerId,
442 saml::SAMLAuthenticationStatement* s,
443 saml::SAMLResponse* r=NULL,
444 const shibboleth::IRoleDescriptor* source=NULL,
448 virtual void remove(const char* key);
450 virtual void cleanup();
452 bool m_storeAttributes;
455 ISessionCache* m_cache;
456 CondWait* shutdown_wait;
458 Thread* cleanup_thread;
460 static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
463 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e) : MySQLBase(e), m_storeAttributes(false)
466 saml::NDC ndc("ShibMySQLCCache");
469 log = &(Category::getInstance("shibmysql.SessionCache"));
471 shutdown_wait = CondWait::create();
474 m_cache = dynamic_cast<ISessionCache*>(
475 SAMLConfig::getConfig().getPlugMgr().newPlugin(
476 "edu.internet2.middleware.shibboleth.sp.provider.MemorySessionCacheProvider", e
480 // Load our configuration details...
481 const XMLCh* tag=m_root->getAttributeNS(NULL,storeAttributes);
482 if (tag && *tag && (*tag==chLatin_t || *tag==chDigit_1))
483 m_storeAttributes=true;
485 // Initialize the cleanup thread
486 cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
489 ShibMySQLCCache::~ShibMySQLCCache()
492 shutdown_wait->signal();
493 cleanup_thread->join(NULL);
498 ISessionCacheEntry* ShibMySQLCCache::find(const char* key, const IApplication* application)
501 saml::NDC ndc("find");
504 ISessionCacheEntry* res = m_cache->find(key, application);
507 log->debug("Looking in database...");
509 // nothing cached; see if this exists in the database
510 string q = string("SELECT application_id,UNIX_TIMESTAMP(ctime),UNIX_TIMESTAMP(atime),addr,profile,provider,statement,response FROM state WHERE cookie='") + key + "' LIMIT 1";
512 MYSQL* mysql = getMYSQL();
513 if (mysql_query(mysql, q.c_str())) {
514 const char* err=mysql_error(mysql);
515 log->error("Error searching for %s: %s", key, err);
516 if (isCorrupt(err) && repairTable(mysql,"state")) {
517 if (mysql_query(mysql, q.c_str()))
518 log->error("Error retrying search for %s: %s", key, mysql_error(mysql));
522 MYSQL_RES* rows = mysql_store_result(mysql);
524 // Nope, doesn't exist.
528 // Make sure we got 1 and only 1 rows.
529 if (mysql_num_rows(rows) != 1) {
530 log->error("Select returned wrong number of rows: %d", mysql_num_rows(rows));
531 mysql_free_result(rows);
535 log->debug("Match found. Parsing...");
548 // Pull apart the row and process the results
549 MYSQL_ROW row = mysql_fetch_row(rows);
550 if (strcmp(application->getId(),row[0])) {
551 log->crit("An application (%s) attempted to access another application's (%s) session!", application->getId(), row[0]);
552 mysql_free_result(rows);
556 Metadata m(application->getMetadataProviders());
557 const IEntityDescriptor* provider=m.lookup(row[5]);
559 log->crit("no metadata found for identity provider (%s) responsible for the session.", row[5]);
560 mysql_free_result(rows);
564 SAMLAuthenticationStatement* s=NULL;
565 SAMLResponse* r=NULL;
566 ShibProfile profile=static_cast<ShibProfile>(atoi(row[4]));
567 const IRoleDescriptor* role=NULL;
568 if (profile==SAML11_POST || profile==SAML11_ARTIFACT)
569 role=provider->getIDPSSODescriptor(saml::XML::SAML11_PROTOCOL_ENUM);
570 else if (profile==SAML10_POST || profile==SAML10_ARTIFACT)
571 role=provider->getIDPSSODescriptor(saml::XML::SAML10_PROTOCOL_ENUM);
574 "no matching IdP role for profile (%s) found for identity provider (%s) responsible for the session.", row[4], row[5]
576 mysql_free_result(rows);
580 // Try to parse the SAML data
582 istringstream istr(row[6]);
583 s = new SAMLAuthenticationStatement(istr);
585 istringstream istr2(row[7]);
586 r = new SAMLResponse(istr2);
589 catch (SAMLException& e) {
590 log->error(string("caught SAML exception while loading objects from SQL record: ") + e.what());
593 mysql_free_result(rows);
598 log->error("caught unknown exception while loading objects from SQL record");
601 mysql_free_result(rows);
606 // Insert it into the memory cache
620 // Free the results, and then re-run the 'find' query
621 mysql_free_result(rows);
622 res = m_cache->find(key,application);
627 return new ShibMySQLCCacheEntry(key, res, this);
630 void ShibMySQLCCache::insert(
632 const IApplication* application,
633 const char* client_addr,
635 const char* providerId,
636 saml::SAMLAuthenticationStatement* s,
637 saml::SAMLResponse* r,
638 const shibboleth::IRoleDescriptor* source,
644 saml::NDC ndc("insert");
648 q << "INSERT INTO state VALUES('" << key << "','" << application->getId() << "',";
652 q << "FROM_UNIXTIME(" << created << "),";
656 q << "FROM_UNIXTIME(" << accessed << "),'";
657 q << client_addr << "'," << profile << ",'" << providerId << "',";
658 if (m_storeAttributes && r) {
659 auto_ptr_char id(r->getId());
660 q << "'" << id.get() << "','" << *r << "','";
666 log->debug("Query: %s", q.str().c_str());
668 // then add it to the database
669 MYSQL* mysql = getMYSQL();
670 if (mysql_query(mysql, q.str().c_str())) {
671 const char* err=mysql_error(mysql);
672 log->error("Error inserting %s: %s", key, err);
673 if (isCorrupt(err) && repairTable(mysql,"state")) {
675 if (mysql_query(mysql, q.str().c_str())) {
676 log->error("Error inserting %s: %s", key, mysql_error(mysql));
677 throw SAMLException("ShibMySQLCCache::insert(): insertion failed");
681 throw SAMLException("ShibMySQLCCache::insert(): insertion failed");
684 // Add it to the memory cache
685 m_cache->insert(key, application, client_addr, profile, providerId, s, r, source, created, accessed);
688 void ShibMySQLCCache::remove(const char* key)
691 saml::NDC ndc("remove");
694 // Remove the cached version
695 m_cache->remove(key);
697 // Remove from the database
698 string q = string("DELETE FROM state WHERE cookie='") + key + "'";
699 MYSQL* mysql = getMYSQL();
700 if (mysql_query(mysql, q.c_str())) {
701 const char* err=mysql_error(mysql);
702 log->error("Error deleting entry %s: %s", key, err);
703 if (isCorrupt(err) && repairTable(mysql,"state")) {
705 if (mysql_query(mysql, q.c_str()))
706 log->error("Error deleting entry %s: %s", key, mysql_error(mysql));
711 void ShibMySQLCCache::cleanup()
714 saml::NDC ndc("cleanup");
717 Mutex* mutex = Mutex::create();
718 MySQLBase::thread_init();
721 int timeout_life = 0;
723 // Load our configuration details...
724 const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
726 rerun_timer = XMLString::parseInt(tag);
728 // search for 'mysql-cache-timeout' and then the regular cache timeout
729 tag=m_root->getAttributeNS(NULL,mysqlTimeout);
731 timeout_life = XMLString::parseInt(tag);
733 tag=m_root->getAttributeNS(NULL,cacheTimeout);
735 timeout_life = XMLString::parseInt(tag);
738 if (rerun_timer <= 0)
739 rerun_timer = 300; // rerun every 5 minutes
741 if (timeout_life <= 0)
742 timeout_life = 28800; // timeout after 8 hours
746 MYSQL* mysql = getMYSQL();
748 while (shutdown == false) {
749 shutdown_wait->timedwait(mutex, rerun_timer);
751 if (shutdown == true)
754 // Find all the entries in the database that haven't been used
755 // recently In particular, find all entries that have not been
756 // accessed in 'timeout_life' seconds.
758 q << "SELECT cookie FROM state WHERE " <<
759 "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
761 if (mysql_query(mysql, q.str().c_str())) {
762 const char* err=mysql_error(mysql);
763 log->error("Error searching for old items: %s", err);
764 if (isCorrupt(err) && repairTable(mysql,"state")) {
765 if (mysql_query(mysql, q.str().c_str()))
766 log->error("Error re-searching for old items: %s", mysql_error(mysql));
770 MYSQL_RES* rows = mysql_store_result(mysql);
774 if (mysql_num_fields(rows) != 1) {
775 log->error("Wrong number of columns, 1 != %d", mysql_num_fields(rows));
776 mysql_free_result(rows);
780 // For each row, remove the entry from the database.
782 while ((row = mysql_fetch_row(rows)) != NULL)
785 mysql_free_result(rows);
788 log->info("cleanup thread exiting...");
792 MySQLBase::thread_end();
796 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
798 ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
800 // First, let's block all signals
801 Thread::mask_all_signals();
803 // Now run the cleanup process.
808 /*************************************************************************
809 * The CCacheEntry here is mostly a wrapper around the "memory"
810 * cacheentry provided by shibboleth. The only difference is that we
811 * intercept isSessionValid() so that we can "touch()" the
812 * database if the session is still valid and getResponse() so we can
813 * store the data if we need to.
816 bool ShibMySQLCCacheEntry::isValid(time_t lifetime, time_t timeout) const
818 bool res = m_cacheEntry->isValid(lifetime, timeout);
824 bool ShibMySQLCCacheEntry::touch() const
826 string q=string("UPDATE state SET atime=NOW() WHERE cookie='") + m_key + "'";
828 MYSQL* mysql = m_cache->getMYSQL();
829 if (mysql_query(mysql, q.c_str())) {
830 m_cache->log->info("Error updating timestamp on %s: %s", m_key.c_str(), mysql_error(mysql));
836 ISessionCacheEntry::CachedResponse ShibMySQLCCacheEntry::getResponse()
838 // Let the memory cache do the work first.
839 // If we're hands off, just pass it back.
840 if (!m_cache->m_storeAttributes)
841 return m_cacheEntry->getResponse();
843 CachedResponse r=m_cacheEntry->getResponse();
844 if (r.empty()) return r;
846 // Load the key from state if needed.
848 string qselect=string("SELECT response_id from state WHERE cookie='") + m_key + "' LIMIT 1";
849 MYSQL* mysql = m_cache->getMYSQL();
850 if (mysql_query(mysql, qselect.c_str())) {
851 const char* err=mysql_error(mysql);
852 m_cache->log->error("error accessing response ID for %s: %s", m_key.c_str(), err);
853 if (isCorrupt(err) && m_cache->repairTable(mysql,"state")) {
855 if (mysql_query(mysql, qselect.c_str())) {
856 m_cache->log->error("error accessing response ID for %s: %s", m_key.c_str(), mysql_error(mysql));
861 MYSQL_RES* rows = mysql_store_result(mysql);
863 // Make sure we got 1 and only 1 row.
864 if (!rows || mysql_num_rows(rows) != 1) {
865 m_cache->log->error("select returned wrong number of rows");
866 if (rows) mysql_free_result(rows);
870 MYSQL_ROW row=mysql_fetch_row(rows);
872 m_responseId=XMLString::transcode(row[0]);
873 mysql_free_result(rows);
876 // Compare it with what we have now.
877 if (m_responseId && !XMLString::compareString(m_responseId,r.unfiltered->getId()))
880 // No match, so we need to update our copy.
881 if (m_responseId) XMLString::release(&m_responseId);
882 m_responseId = XMLString::replicate(r.unfiltered->getId());
883 auto_ptr_char id(m_responseId);
886 q << "UPDATE state SET response_id='" << id.get() << "',response='" << *r.unfiltered << "' WHERE cookie='" << m_key << "'";
887 m_cache->log->debug("Query: %s", q.str().c_str());
889 MYSQL* mysql = m_cache->getMYSQL();
890 if (mysql_query(mysql, q.str().c_str())) {
891 const char* err=mysql_error(mysql);
892 m_cache->log->error("Error updating response for %s: %s", m_key.c_str(), err);
893 if (isCorrupt(err) && m_cache->repairTable(mysql,"state")) {
895 if (mysql_query(mysql, q.str().c_str()))
896 m_cache->log->error("Error updating response for %s: %s", m_key.c_str(), mysql_error(mysql));
903 class MySQLReplayCache : public MySQLBase, virtual public IReplayCache
906 MySQLReplayCache(const DOMElement* e);
907 virtual ~MySQLReplayCache() {}
909 void thread_init() {MySQLBase::thread_init();}
910 void thread_end() {MySQLBase::thread_end();}
912 bool check(const XMLCh* str, time_t expires) {auto_ptr_XMLCh temp(str); return check(temp.get(),expires);}
913 bool check(const char* str, time_t expires);
916 MySQLReplayCache::MySQLReplayCache(const DOMElement* e) : MySQLBase(e)
919 saml::NDC ndc("MySQLReplayCache");
922 log = &(Category::getInstance("shibmysql.ReplayCache"));
925 bool MySQLReplayCache::check(const char* str, time_t expires)
928 saml::NDC ndc("check");
931 // Remove expired entries
932 string q = string("DELETE FROM replay WHERE expires < NOW()");
933 MYSQL* mysql = getMYSQL();
934 if (mysql_query(mysql, q.c_str())) {
935 const char* err=mysql_error(mysql);
936 log->error("Error deleting expired entries: %s", err);
937 if (isCorrupt(err) && repairTable(mysql,"replay")) {
939 if (mysql_query(mysql, q.c_str()))
940 log->error("Error deleting expired entries: %s", mysql_error(mysql));
944 string q2 = string("SELECT id FROM replay WHERE id='") + str + "'";
945 if (mysql_query(mysql, q2.c_str())) {
946 const char* err=mysql_error(mysql);
947 log->error("Error searching for %s: %s", str, err);
948 if (isCorrupt(err) && repairTable(mysql,"replay")) {
949 if (mysql_query(mysql, q2.c_str())) {
950 log->error("Error retrying search for %s: %s", str, mysql_error(mysql));
951 throw SAMLException("Replay cache failed, please inform application support staff.");
955 throw SAMLException("Replay cache failed, please inform application support staff.");
959 MYSQL_RES* rows = mysql_store_result(mysql);
960 if (rows && mysql_num_rows(rows)>0) {
961 mysql_free_result(rows);
966 q3 << "INSERT INTO replay VALUES('" << str << "'," << "FROM_UNIXTIME(" << expires << "))";
968 // then add it to the database
969 if (mysql_query(mysql, q3.str().c_str())) {
970 const char* err=mysql_error(mysql);
971 log->error("Error inserting %s: %s", str, err);
972 if (isCorrupt(err) && repairTable(mysql,"state")) {
974 if (mysql_query(mysql, q3.str().c_str())) {
975 log->error("Error inserting %s: %s", str, mysql_error(mysql));
976 throw SAMLException("Replay cache failed, please inform application support staff.");
980 throw SAMLException("Replay cache failed, please inform application support staff.");
986 /*************************************************************************
987 * The registration functions here...
990 IPlugIn* new_mysql_ccache(const DOMElement* e)
992 return new ShibMySQLCCache(e);
995 IPlugIn* new_mysql_replay(const DOMElement* e)
997 return new MySQLReplayCache(e);
1000 #define REPLAYPLUGINTYPE "edu.internet2.middleware.shibboleth.sp.provider.MySQLReplayCacheProvider"
1001 #define SESSIONPLUGINTYPE "edu.internet2.middleware.shibboleth.sp.provider.MySQLSessionCacheProvider"
1003 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
1005 // register this ccache type
1006 SAMLConfig::getConfig().getPlugMgr().regFactory(REPLAYPLUGINTYPE, &new_mysql_replay);
1007 SAMLConfig::getConfig().getPlugMgr().regFactory(SESSIONPLUGINTYPE, &new_mysql_ccache);
1011 extern "C" void SHIBMYSQL_EXPORTS saml_extension_term()
1015 SAMLConfig::getConfig().getPlugMgr().unregFactory(REPLAYPLUGINTYPE);
1016 SAMLConfig::getConfig().getPlugMgr().unregFactory(SESSIONPLUGINTYPE);