729abfb66f1e6d737bb28c36bdc01f76414bbef5
[shibboleth/cpp-sp.git] / shib-mysql-ccache / shib-mysql-ccache.cpp
1 /*
2  *  Copyright 2001-2005 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * shib-mysql-ccache.cpp: Shibboleth Credential Cache using MySQL.
19  *
20  * Created by:  Derek Atkins <derek@ihtfp.com>
21  *
22  * $Id$
23  */
24
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.
28  *
29  * Short-term data is cached in memory as SAML objects in the layer 2
30  * cache.
31  */
32
33 // eventually we might be able to support autoconf via cygwin...
34 #if defined (_MSC_VER) || defined(__BORLANDC__)
35 # include "config_win32.h"
36 #else
37 # include "config.h"
38 #endif
39
40 #ifdef WIN32
41 # define SHIBMYSQL_EXPORTS __declspec(dllexport)
42 #else
43 # define SHIBMYSQL_EXPORTS
44 #endif
45
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49
50 #include <shib-target/shib-target.h>
51 #include <shib/shib-threads.h>
52 #include <log4cpp/Category.hh>
53
54 #include <sstream>
55 #include <stdexcept>
56
57 #include <mysql.h>
58
59 // wanted to use MySQL codes for this, but can't seem to get back a 145
60 #define isCorrupt(s) strstr(s,"(errno: 145)")
61
62 #ifdef HAVE_LIBDMALLOCXX
63 #include <dmalloc.h>
64 #endif
65
66 using namespace std;
67 using namespace saml;
68 using namespace shibboleth;
69 using namespace shibtarget;
70 using namespace log4cpp;
71
72 #define PLUGIN_VER_MAJOR 2
73 #define PLUGIN_VER_MINOR 0
74
75 #define STATE_TABLE \
76   "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, " \
77   "application_id VARCHAR(255)," \
78   "ctime TIMESTAMP," \
79   "atime TIMESTAMP," \
80   "addr VARCHAR(128)," \
81   "profile INT," \
82   "provider VARCHAR(256)," \
83   "response_id VARCHAR(128)," \
84   "response TEXT," \
85   "statement TEXT)"
86
87 #define REPLAY_TABLE \
88   "CREATE TABLE replay (id VARCHAR(255) PRIMARY KEY, " \
89   "expires TIMESTAMP, " \
90   "INDEX (expires))"
91
92 static const XMLCh Argument[] =
93 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
94 static const XMLCh cleanupInterval[] =
95 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
96   chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
97 };
98 static const XMLCh cacheTimeout[] =
99 { 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 };
100 static const XMLCh mysqlTimeout[] =
101 { 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 };
102 static const XMLCh storeAttributes[] =
103 { 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 };
104
105 class MySQLBase
106 {
107 public:
108   MySQLBase(const DOMElement* e);
109   virtual ~MySQLBase();
110
111   void thread_init();
112   void thread_end() {}
113
114   MYSQL* getMYSQL() const;
115   bool repairTable(MYSQL*&, const char* table);
116
117   log4cpp::Category* log;
118
119 protected:
120   ThreadKey* m_mysql;
121   const DOMElement* m_root; // can only use this during initialization
122
123   bool initialized;
124
125   void createDatabase(MYSQL*, int major, int minor);
126   void upgradeDatabase(MYSQL*);
127   void getVersion(MYSQL*, int* major_p, int* minor_p);
128 };
129
130 // Forward declarations
131 static void mysqlInit(const DOMElement* e, Category& log);
132
133 extern "C" void shib_mysql_destroy_handle(void* data)
134 {
135   MYSQL* mysql = (MYSQL*) data;
136   if (mysql) mysql_close(mysql);
137 }
138
139 MySQLBase::MySQLBase(const DOMElement* e) : m_root(e)
140 {
141 #ifdef _DEBUG
142   saml::NDC ndc("MySQLBase");
143 #endif
144   log = &(Category::getInstance("shibmysql.MySQLBase"));
145
146   m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
147
148   initialized = false;
149   mysqlInit(e,*log);
150   thread_init();
151   initialized = true;
152 }
153
154 MySQLBase::~MySQLBase()
155 {
156   thread_end();
157
158   delete m_mysql;
159 }
160
161 MYSQL* MySQLBase::getMYSQL() const
162 {
163   return (MYSQL*)m_mysql->getData();
164 }
165
166 void MySQLBase::thread_init()
167 {
168 #ifdef _DEBUG
169   saml::NDC ndc("thread_init");
170 #endif
171
172   // Connect to the database
173   MYSQL* mysql = mysql_init(NULL);
174   if (!mysql) {
175     log->error("mysql_init failed");
176     mysql_close(mysql);
177     throw SAMLException("MySQLBase::thread_init(): mysql_init() failed");
178   }
179
180   if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
181     if (initialized) {
182       log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
183       mysql_close(mysql);
184       throw SAMLException("MySQLBase::thread_init(): mysql_real_connect() failed");
185     } else {
186       log->info("mysql_real_connect failed: %s.  Trying to create", mysql_error(mysql));
187
188       // This will throw an exception if it fails.
189       createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
190     }
191   }
192
193   int major = -1, minor = -1;
194   getVersion (mysql, &major, &minor);
195
196   // Make sure we've got the right version
197   if (major != PLUGIN_VER_MAJOR || minor != PLUGIN_VER_MINOR) {
198    
199     // If we're capable, try upgrading on the fly...
200     if (major == 0  || major == 1) {
201        upgradeDatabase(mysql);
202     }
203     else {
204         mysql_close(mysql);
205         log->crit("Unknown database version: %d.%d", major, minor);
206         throw SAMLException("MySQLBase::thread_init(): Unknown database version");
207     }
208   }
209
210   // We're all set.. Save off the handle for this thread.
211   m_mysql->setData(mysql);
212 }
213
214 bool MySQLBase::repairTable(MYSQL*& mysql, const char* table)
215 {
216   string q = string("REPAIR TABLE ") + table;
217   if (mysql_query(mysql, q.c_str())) {
218     log->error("Error repairing table %s: %s", table, mysql_error(mysql));
219     return false;
220   }
221
222   // seems we have to recycle the connection to get the thread to keep working
223   // other threads seem to be ok, but we should monitor that
224   mysql_close(mysql);
225   m_mysql->setData(NULL);
226   thread_init();
227   mysql=getMYSQL();
228   return true;
229 }
230
231 void MySQLBase::createDatabase(MYSQL* mysql, int major, int minor)
232 {
233   log->info("Creating database.");
234
235   MYSQL* ms = NULL;
236   try {
237     ms = mysql_init(NULL);
238     if (!ms) {
239       log->crit("mysql_init failed");
240       throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_init failed");
241     }
242
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");
246     }
247
248     if (mysql_query(ms, "CREATE DATABASE shar")) {
249       log->crit("cannot create shar database: %s", mysql_error(ms));
250       throw SAMLException("ShibMySQLCCache::createDatabase(): create db cmd failed");
251     }
252
253     if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
254       log->crit("cannot open SHAR database");
255       throw SAMLException("ShibMySQLCCache::createDatabase(): mysql_real_connect to plugin db failed");
256     }
257
258     mysql_close(ms);
259     
260   }
261   catch (SAMLException&) {
262     if (ms)
263       mysql_close(ms);
264     mysql_close(mysql);
265     throw;
266   }
267
268   // Now create the tables if they don't exist
269   log->info("Creating database tables");
270
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");
274   }
275
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");
279   }
280
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");
284   }
285
286   ostringstream q;
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");
291   }
292 }
293
294 void MySQLBase::upgradeDatabase(MYSQL* mysql)
295 {
296     if (mysql_query(mysql, "DROP TABLE state")) {
297         log->error("Error dropping old session state table: %s", mysql_error(mysql));
298     }
299
300     if (mysql_query(mysql,STATE_TABLE)) {
301         log->error ("Error creating state table: %s", mysql_error(mysql));
302         throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating state table");
303     }
304
305     if (mysql_query(mysql,REPLAY_TABLE)) {
306         log->error ("Error creating replay table: %s", mysql_error(mysql));
307         throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error creating replay table");
308     }
309
310     ostringstream q;
311     q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
312     if (mysql_query(mysql, q.str().c_str())) {
313         log->error ("Error updating version: %s", mysql_error(mysql));
314         throw SAMLException("ShibMySQLCCache::upgradeDatabase(): error updating version");
315     }
316 }
317
318 void MySQLBase::getVersion(MYSQL* mysql, int* major_p, int* minor_p)
319 {
320   // grab the version number from the database
321   if (mysql_query(mysql, "SELECT * FROM version"))
322     log->error ("Error reading version: %s", mysql_error(mysql));
323
324   MYSQL_RES* rows = mysql_store_result(mysql);
325   if (rows) {
326     if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2)  {
327       MYSQL_ROW row = mysql_fetch_row(rows);
328
329       int major = row[0] ? atoi(row[0]) : -1;
330       int minor = row[1] ? atoi(row[1]) : -1;
331       log->debug("opening database version %d.%d", major, minor);
332       
333       mysql_free_result (rows);
334
335       *major_p = major;
336       *minor_p = minor;
337       return;
338
339     } else {
340       // Wrong number of rows or wrong number of fields...
341
342       log->crit("Houston, we've got a problem with the database...");
343       mysql_free_result (rows);
344       throw SAMLException("ShibMySQLCCache::getVersion(): version verification failed");
345     }
346   }
347   log->crit("MySQL Read Failed in version verificatoin");
348   throw SAMLException("ShibMySQLCCache::getVersion(): error reading version");
349 }
350
351 static void mysqlInit(const DOMElement* e, Category& log)
352 {
353   static bool done = false;
354   if (done) {
355     log.info("MySQL embedded server already initialized");
356     return;
357   }
358   log.info("initializing MySQL embedded server");
359
360   // Setup the argument array
361   vector<string> arg_array;
362   arg_array.push_back("shibboleth");
363
364   // grab any MySQL parameters from the config file
365   e=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
366   while (e) {
367       auto_ptr_char arg(e->getFirstChild()->getNodeValue());
368       if (arg.get())
369           arg_array.push_back(arg.get());
370       e=saml::XML::getNextSiblingElement(e,shibtarget::XML::SHIBTARGET_NS,Argument);
371   }
372
373   // Compute the argument array
374   int arg_count = arg_array.size();
375   const char** args=new const char*[arg_count];
376   for (int i = 0; i < arg_count; i++)
377     args[i] = arg_array[i].c_str();
378
379   // Initialize MySQL with the arguments
380   mysql_server_init(arg_count, (char **)args, NULL);
381
382   delete[] args;
383   done = true;
384 }  
385
386 class ShibMySQLCCache;
387 class ShibMySQLCCacheEntry : public ISessionCacheEntry
388 {
389 public:
390   ShibMySQLCCacheEntry(const char* key, ISessionCacheEntry* entry, ShibMySQLCCache* cache)
391     : m_cacheEntry(entry), m_key(key), m_cache(cache), m_responseId(NULL) {}
392   ~ShibMySQLCCacheEntry() {if (m_responseId) XMLString::release(&m_responseId);}
393
394   virtual void lock() {}
395   virtual void unlock() { m_cacheEntry->unlock(); delete this; }
396   virtual bool isValid(time_t lifetime, time_t timeout) const;
397   virtual const char* getClientAddress() const { return m_cacheEntry->getClientAddress(); }
398   virtual ShibProfile getProfile() const { return m_cacheEntry->getProfile(); }
399   virtual const char* getProviderId() const { return m_cacheEntry->getProviderId(); }
400   virtual const SAMLAuthenticationStatement* getAuthnStatement() const { return m_cacheEntry->getAuthnStatement(); }
401   virtual CachedResponse getResponse();
402
403 private:
404   bool touch() const;
405
406   ShibMySQLCCache* m_cache;
407   ISessionCacheEntry* m_cacheEntry;
408   string m_key;
409   XMLCh* m_responseId;
410 };
411
412 class ShibMySQLCCache : public MySQLBase, virtual public ISessionCache
413 {
414 public:
415   ShibMySQLCCache(const DOMElement* e);
416   virtual ~ShibMySQLCCache();
417
418   virtual void thread_init() {MySQLBase::thread_init();}
419   virtual void thread_end() {MySQLBase::thread_end();}
420
421   virtual string generateKey() const {return m_cache->generateKey();}
422   virtual ISessionCacheEntry* find(const char* key, const IApplication* application);
423   virtual void insert(
424     const char* key,
425     const IApplication* application,
426     const char* client_addr,
427     ShibProfile profile,
428     const char* providerId,
429     saml::SAMLAuthenticationStatement* s,
430     saml::SAMLResponse* r=NULL,
431     const shibboleth::IRoleDescriptor* source=NULL,
432     time_t created=0,
433     time_t accessed=0
434     );
435   virtual void remove(const char* key);
436
437   virtual void cleanup();
438
439   bool m_storeAttributes;
440
441 private:
442   ISessionCache* m_cache;
443   CondWait* shutdown_wait;
444   bool shutdown;
445   Thread* cleanup_thread;
446
447   static void* cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
448 };
449
450 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e) : MySQLBase(e), m_storeAttributes(false)
451 {
452 #ifdef _DEBUG
453   saml::NDC ndc("ShibMySQLCCache");
454 #endif
455
456   log = &(Category::getInstance("shibmysql.SessionCache"));
457
458   shutdown_wait = CondWait::create();
459   shutdown = false;
460
461   m_cache = dynamic_cast<ISessionCache*>(
462       SAMLConfig::getConfig().getPlugMgr().newPlugin(
463         "edu.internet2.middleware.shibboleth.sp.provider.MemorySessionCacheProvider", e
464         )
465     );
466     
467   // Load our configuration details...
468   const XMLCh* tag=m_root->getAttributeNS(NULL,storeAttributes);
469   if (tag && *tag && (*tag==chLatin_t || *tag==chDigit_1))
470     m_storeAttributes=true;
471
472   // Initialize the cleanup thread
473   cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
474 }
475
476 ShibMySQLCCache::~ShibMySQLCCache()
477 {
478   shutdown = true;
479   shutdown_wait->signal();
480   cleanup_thread->join(NULL);
481
482   delete m_cache;
483 }
484
485 ISessionCacheEntry* ShibMySQLCCache::find(const char* key, const IApplication* application)
486 {
487 #ifdef _DEBUG
488   saml::NDC ndc("find");
489 #endif
490
491   ISessionCacheEntry* res = m_cache->find(key, application);
492   if (!res) {
493
494     log->debug("Looking in database...");
495
496     // nothing cached; see if this exists in the database
497     string q = string("SELECT application_id,UNIX_TIMESTAMP(ctime),UNIX_TIMESTAMP(atime),addr,profile,provider,statement,response FROM state WHERE cookie='") + key + "' LIMIT 1";
498
499     MYSQL* mysql = getMYSQL();
500     if (mysql_query(mysql, q.c_str())) {
501       const char* err=mysql_error(mysql);
502       log->error("Error searching for %s: %s", key, err);
503       if (isCorrupt(err) && repairTable(mysql,"state")) {
504         if (mysql_query(mysql, q.c_str()))
505           log->error("Error retrying search for %s: %s", key, mysql_error(mysql));
506       }
507     }
508
509     MYSQL_RES* rows = mysql_store_result(mysql);
510
511     // Nope, doesn't exist.
512     if (!rows)
513       return NULL;
514
515     // Make sure we got 1 and only 1 rows.
516     if (mysql_num_rows(rows) != 1) {
517       log->error("Select returned wrong number of rows: %d", mysql_num_rows(rows));
518       mysql_free_result(rows);
519       return NULL;
520     }
521
522     log->debug("Match found.  Parsing...");
523     
524     /* Columns in query:
525         0: application_id
526         1: ctime
527         2: atime
528         3: address
529         4: profile
530         5: provider
531         6: statement
532         7: response
533      */
534
535     // Pull apart the row and process the results
536     MYSQL_ROW row = mysql_fetch_row(rows);
537     if (strcmp(application->getId(),row[0])) {
538         log->crit("An application (%s) attempted to access another application's (%s) session!", application->getId(), row[0]);
539         mysql_free_result(rows);
540         return NULL;
541     }
542
543     Metadata m(application->getMetadataProviders());
544     const IEntityDescriptor* provider=m.lookup(row[5]);
545     if (!provider) {
546         log->crit("no metadata found for identity provider (%s) responsible for the session.", row[5]);
547         mysql_free_result(rows);
548         return NULL;
549     }
550
551     SAMLAuthenticationStatement* s=NULL;
552     SAMLResponse* r=NULL;
553     ShibProfile profile=static_cast<ShibProfile>(atoi(row[4]));
554     const IRoleDescriptor* role=NULL;
555     if (profile==SAML11_POST || profile==SAML11_ARTIFACT)
556         role=provider->getIDPSSODescriptor(saml::XML::SAML11_PROTOCOL_ENUM);
557     else if (profile==SAML10_POST || profile==SAML10_ARTIFACT)
558         role=provider->getIDPSSODescriptor(saml::XML::SAML10_PROTOCOL_ENUM);
559     if (!role) {
560         log->crit(
561             "no matching IdP role for profile (%s) found for identity provider (%s) responsible for the session.", row[4], row[5]
562             );
563         mysql_free_result(rows);
564         return NULL;
565     }
566
567     // Try to parse the SAML data
568     try {
569         istringstream istr(row[6]);
570         s = new SAMLAuthenticationStatement(istr);
571         if (row[7]) {
572             istringstream istr2(row[7]);
573             r = new SAMLResponse(istr2);
574         }
575     }
576     catch (SAMLException& e) {
577         log->error(string("caught SAML exception while loading objects from SQL record: ") + e.what());
578         delete s;
579         delete r;
580         mysql_free_result(rows);
581         return NULL;
582     }
583 #ifndef _DEBUG
584     catch (...) {
585         log->error("caught unknown exception while loading objects from SQL record");
586         delete s;
587         delete r;
588         mysql_free_result(rows);
589         return NULL;
590     }
591 #endif
592
593     // Insert it into the memory cache
594     m_cache->insert(
595         key,
596         application,
597         row[3],
598         profile,
599         row[5],
600         s,
601         r,
602         role,
603         atoi(row[1]),
604         atoi(row[2])
605         );
606
607     // Free the results, and then re-run the 'find' query
608     mysql_free_result(rows);
609     res = m_cache->find(key,application);
610     if (!res)
611       return NULL;
612   }
613
614   return new ShibMySQLCCacheEntry(key, res, this);
615 }
616
617 void ShibMySQLCCache::insert(
618     const char* key,
619     const IApplication* application,
620     const char* client_addr,
621     ShibProfile profile,
622     const char* providerId,
623     saml::SAMLAuthenticationStatement* s,
624     saml::SAMLResponse* r,
625     const shibboleth::IRoleDescriptor* source,
626     time_t created,
627     time_t accessed
628     )
629 {
630 #ifdef _DEBUG
631   saml::NDC ndc("insert");
632 #endif
633   
634   ostringstream q;
635   q << "INSERT INTO state VALUES('" << key << "','" << application->getId() << "',";
636   if (created==0)
637     q << "NOW(),";
638   else
639     q << "FROM_UNIXTIME(" << created << "),";
640   if (accessed==0)
641     q << "NOW(),'";
642   else
643     q << "FROM_UNIXTIME(" << accessed << "),'";
644   q << client_addr << "'," << profile << ",'" << providerId << "',";
645   if (m_storeAttributes && r) {
646     auto_ptr_char id(r->getId());
647     q << "'" << id.get() << "','" << *r << "','";
648   }
649   else
650     q << "null,null,'";
651   q << *s << "')";
652
653   log->debug("Query: %s", q.str().c_str());
654
655   // then add it to the database
656   MYSQL* mysql = getMYSQL();
657   if (mysql_query(mysql, q.str().c_str())) {
658     const char* err=mysql_error(mysql);
659     log->error("Error inserting %s: %s", key, err);
660     if (isCorrupt(err) && repairTable(mysql,"state")) {
661         // Try again...
662         if (mysql_query(mysql, q.str().c_str())) {
663           log->error("Error inserting %s: %s", key, mysql_error(mysql));
664           throw SAMLException("ShibMySQLCCache::insert(): insertion failed");
665         }
666     }
667     else
668         throw SAMLException("ShibMySQLCCache::insert(): insertion failed");
669   }
670
671   // Add it to the memory cache
672   m_cache->insert(key, application, client_addr, profile, providerId, s, r, source, created, accessed);
673 }
674
675 void ShibMySQLCCache::remove(const char* key)
676 {
677 #ifdef _DEBUG
678   saml::NDC ndc("remove");
679 #endif
680
681   // Remove the cached version
682   m_cache->remove(key);
683
684   // Remove from the database
685   string q = string("DELETE FROM state WHERE cookie='") + key + "'";
686   MYSQL* mysql = getMYSQL();
687   if (mysql_query(mysql, q.c_str())) {
688     const char* err=mysql_error(mysql);
689     log->error("Error deleting entry %s: %s", key, err);
690     if (isCorrupt(err) && repairTable(mysql,"state")) {
691         // Try again...
692         if (mysql_query(mysql, q.c_str()))
693           log->error("Error deleting entry %s: %s", key, mysql_error(mysql));
694     }
695   }
696 }
697
698 void ShibMySQLCCache::cleanup()
699 {
700 #ifdef _DEBUG
701   saml::NDC ndc("cleanup");
702 #endif
703
704   Mutex* mutex = Mutex::create();
705   MySQLBase::thread_init();
706
707   int rerun_timer = 0;
708   int timeout_life = 0;
709
710   // Load our configuration details...
711   const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
712   if (tag && *tag)
713     rerun_timer = XMLString::parseInt(tag);
714
715   // search for 'mysql-cache-timeout' and then the regular cache timeout
716   tag=m_root->getAttributeNS(NULL,mysqlTimeout);
717   if (tag && *tag)
718     timeout_life = XMLString::parseInt(tag);
719   else {
720       tag=m_root->getAttributeNS(NULL,cacheTimeout);
721       if (tag && *tag)
722         timeout_life = XMLString::parseInt(tag);
723   }
724   
725   if (rerun_timer <= 0)
726     rerun_timer = 300;          // rerun every 5 minutes
727
728   if (timeout_life <= 0)
729     timeout_life = 28800;       // timeout after 8 hours
730
731   mutex->lock();
732
733   MYSQL* mysql = getMYSQL();
734
735   while (shutdown == false) {
736     shutdown_wait->timedwait(mutex, rerun_timer);
737
738     if (shutdown == true)
739       break;
740
741     // Find all the entries in the database that haven't been used
742     // recently In particular, find all entries that have not been
743     // accessed in 'timeout_life' seconds.
744     ostringstream q;
745     q << "SELECT cookie FROM state WHERE " <<
746       "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
747
748     if (mysql_query(mysql, q.str().c_str())) {
749       const char* err=mysql_error(mysql);
750       log->error("Error searching for old items: %s", err);
751         if (isCorrupt(err) && repairTable(mysql,"state")) {
752           if (mysql_query(mysql, q.str().c_str()))
753             log->error("Error re-searching for old items: %s", mysql_error(mysql));
754         }
755     }
756
757     MYSQL_RES* rows = mysql_store_result(mysql);
758     if (!rows)
759       continue;
760
761     if (mysql_num_fields(rows) != 1) {
762       log->error("Wrong number of columns, 1 != %d", mysql_num_fields(rows));
763       mysql_free_result(rows);
764       continue;
765     }
766
767     // For each row, remove the entry from the database.
768     MYSQL_ROW row;
769     while ((row = mysql_fetch_row(rows)) != NULL)
770       remove(row[0]);
771
772     mysql_free_result(rows);
773   }
774
775   log->info("cleanup thread exiting...");
776
777   mutex->unlock();
778   delete mutex;
779   MySQLBase::thread_end();
780   Thread::exit(NULL);
781 }
782
783 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
784 {
785   ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
786
787   // First, let's block all signals
788   Thread::mask_all_signals();
789
790   // Now run the cleanup process.
791   cache->cleanup();
792   return NULL;
793 }
794
795 /*************************************************************************
796  * The CCacheEntry here is mostly a wrapper around the "memory"
797  * cacheentry provided by shibboleth.  The only difference is that we
798  * intercept isSessionValid() so that we can "touch()" the
799  * database if the session is still valid and getResponse() so we can
800  * store the data if we need to.
801  */
802
803 bool ShibMySQLCCacheEntry::isValid(time_t lifetime, time_t timeout) const
804 {
805   bool res = m_cacheEntry->isValid(lifetime, timeout);
806   if (res == true)
807     res = touch();
808   return res;
809 }
810
811 bool ShibMySQLCCacheEntry::touch() const
812 {
813   string q=string("UPDATE state SET atime=NOW() WHERE cookie='") + m_key + "'";
814
815   MYSQL* mysql = m_cache->getMYSQL();
816   if (mysql_query(mysql, q.c_str())) {
817     m_cache->log->info("Error updating timestamp on %s: %s", m_key.c_str(), mysql_error(mysql));
818     return false;
819   }
820   return true;
821 }
822
823 ISessionCacheEntry::CachedResponse ShibMySQLCCacheEntry::getResponse()
824 {
825     // Let the memory cache do the work first.
826     // If we're hands off, just pass it back.
827     if (!m_cache->m_storeAttributes)
828         return m_cacheEntry->getResponse();
829     
830     CachedResponse r=m_cacheEntry->getResponse();
831     if (r.empty()) return r;
832     
833     // Load the key from state if needed.
834     if (!m_responseId) {
835         string qselect=string("SELECT response_id from state WHERE cookie='") + m_key + "' LIMIT 1";
836         MYSQL* mysql = m_cache->getMYSQL();
837         if (mysql_query(mysql, qselect.c_str())) {
838             const char* err=mysql_error(mysql);
839             m_cache->log->error("error accessing response ID for %s: %s", m_key.c_str(), err);
840             if (isCorrupt(err) && m_cache->repairTable(mysql,"state")) {
841                 // Try again...
842                 if (mysql_query(mysql, qselect.c_str())) {
843                     m_cache->log->error("error accessing response ID for %s: %s", m_key.c_str(), mysql_error(mysql));
844                     return r;
845                 }
846             }
847         }
848         MYSQL_RES* rows = mysql_store_result(mysql);
849     
850         // Make sure we got 1 and only 1 row.
851         if (!rows || mysql_num_rows(rows) != 1) {
852             m_cache->log->error("select returned wrong number of rows");
853             if (rows) mysql_free_result(rows);
854             return r;
855         }
856         
857         MYSQL_ROW row=mysql_fetch_row(rows);
858         if (row)
859             m_responseId=XMLString::transcode(row[0]);
860         mysql_free_result(rows);
861     }
862     
863     // Compare it with what we have now.
864     if (m_responseId && !XMLString::compareString(m_responseId,r.unfiltered->getId()))
865         return r;
866     
867     // No match, so we need to update our copy.
868     if (m_responseId) XMLString::release(&m_responseId);
869     m_responseId = XMLString::replicate(r.unfiltered->getId());
870     auto_ptr_char id(m_responseId);
871
872     ostringstream q;
873     q << "UPDATE state SET response_id='" << id.get() << "',response='" << *r.unfiltered << "' WHERE cookie='" << m_key << "'";
874     m_cache->log->debug("Query: %s", q.str().c_str());
875
876     MYSQL* mysql = m_cache->getMYSQL();
877     if (mysql_query(mysql, q.str().c_str())) {
878         const char* err=mysql_error(mysql);
879         m_cache->log->error("Error updating response for %s: %s", m_key.c_str(), err);
880         if (isCorrupt(err) && m_cache->repairTable(mysql,"state")) {
881             // Try again...
882             if (mysql_query(mysql, q.str().c_str()))
883               m_cache->log->error("Error updating response for %s: %s", m_key.c_str(), mysql_error(mysql));
884         }
885     }
886     
887     return r;
888 }
889
890 class MySQLReplayCache : public MySQLBase, virtual public IReplayCache
891 {
892 public:
893   MySQLReplayCache(const DOMElement* e);
894   virtual ~MySQLReplayCache() {}
895
896   void thread_init() {MySQLBase::thread_init();}
897   void thread_end() {MySQLBase::thread_end();}
898
899   bool check(const XMLCh* str, time_t expires) {auto_ptr_XMLCh temp(str); return check(temp.get(),expires);}
900   bool check(const char* str, time_t expires);
901 };
902
903 MySQLReplayCache::MySQLReplayCache(const DOMElement* e) : MySQLBase(e)
904 {
905 #ifdef _DEBUG
906   saml::NDC ndc("MySQLReplayCache");
907 #endif
908
909   log = &(Category::getInstance("shibmysql.ReplayCache"));
910 }
911
912 bool MySQLReplayCache::check(const char* str, time_t expires)
913 {
914 #ifdef _DEBUG
915     saml::NDC ndc("check");
916 #endif
917   
918     // Remove expired entries
919     string q = string("DELETE FROM replay WHERE expires < NOW()");
920     MYSQL* mysql = getMYSQL();
921     if (mysql_query(mysql, q.c_str())) {
922         const char* err=mysql_error(mysql);
923         log->error("Error deleting expired entries: %s", err);
924         if (isCorrupt(err) && repairTable(mysql,"replay")) {
925             // Try again...
926             if (mysql_query(mysql, q.c_str()))
927                 log->error("Error deleting expired entries: %s", mysql_error(mysql));
928         }
929     }
930   
931     string q2 = string("SELECT id FROM replay WHERE id='") + str + "'";
932     if (mysql_query(mysql, q2.c_str())) {
933         const char* err=mysql_error(mysql);
934         log->error("Error searching for %s: %s", str, err);
935         if (isCorrupt(err) && repairTable(mysql,"replay")) {
936             if (mysql_query(mysql, q2.c_str())) {
937                 log->error("Error retrying search for %s: %s", str, mysql_error(mysql));
938                 throw SAMLException("Replay cache failed, please inform application support staff.");
939             }
940         }
941         else
942             throw SAMLException("Replay cache failed, please inform application support staff.");
943     }
944
945     // Did we find it?
946     MYSQL_RES* rows = mysql_store_result(mysql);
947     if (rows && mysql_num_rows(rows)>0) {
948       mysql_free_result(rows);
949       return false;
950     }
951
952     ostringstream q3;
953     q3 << "INSERT INTO replay VALUES('" << str << "'," << "FROM_UNIXTIME(" << expires << "))";
954
955     // then add it to the database
956     if (mysql_query(mysql, q3.str().c_str())) {
957         const char* err=mysql_error(mysql);
958         log->error("Error inserting %s: %s", str, err);
959         if (isCorrupt(err) && repairTable(mysql,"state")) {
960             // Try again...
961             if (mysql_query(mysql, q3.str().c_str())) {
962                 log->error("Error inserting %s: %s", str, mysql_error(mysql));
963                 throw SAMLException("Replay cache failed, please inform application support staff.");
964             }
965         }
966         else
967             throw SAMLException("Replay cache failed, please inform application support staff.");
968     }
969     
970     return true;
971 }
972
973 /*************************************************************************
974  * The registration functions here...
975  */
976
977 IPlugIn* new_mysql_ccache(const DOMElement* e)
978 {
979   return new ShibMySQLCCache(e);
980 }
981
982 IPlugIn* new_mysql_replay(const DOMElement* e)
983 {
984   return new MySQLReplayCache(e);
985 }
986
987 #define REPLAYPLUGINTYPE "edu.internet2.middleware.shibboleth.sp.provider.MySQLReplayCacheProvider"
988 #define SESSIONPLUGINTYPE "edu.internet2.middleware.shibboleth.sp.provider.MySQLSessionCacheProvider"
989
990 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
991 {
992   // register this ccache type
993   SAMLConfig::getConfig().getPlugMgr().regFactory(REPLAYPLUGINTYPE, &new_mysql_replay);
994   SAMLConfig::getConfig().getPlugMgr().regFactory(SESSIONPLUGINTYPE, &new_mysql_ccache);
995   return 0;
996 }
997
998 extern "C" void SHIBMYSQL_EXPORTS saml_extension_term()
999 {
1000   // Shutdown MySQL
1001   mysql_server_end();
1002   SAMLConfig::getConfig().getPlugMgr().unregFactory(REPLAYPLUGINTYPE);
1003   SAMLConfig::getConfig().getPlugMgr().unregFactory(SESSIONPLUGINTYPE);
1004 }