New config API and session cache API
[shibboleth/sp.git] / shib-mysql-ccache / shib-mysql-ccache.cpp
1 /*
2  * shib-mysql-ccache.cpp: Shibboleth Credential Cache using MySQL.
3  *
4  * Created by:  Derek Atkins <derek@ihtfp.com>
5  *
6  * $Id$
7  */
8
9 /* This file is loosely based off the Shibboleth Credential Cache.
10  * This plug-in is designed as a two-layer cache.  Layer 1, the
11  * long-term cache, stores data in a MySQL embedded database.  The
12  * data stored in layer 1 is only the session id (cookie), the
13  * "posted" SAML statement (expanded into an XML string), and usage
14  * timestamps.
15  *
16  * Short-term data is cached in memory as SAML objects in the layer 2
17  * cache.  Data like Attribute Authority assertions are stored in
18  * the layer 2 cache.
19  */
20
21 // eventually we might be able to support autoconf via cygwin...
22 #if defined (_MSC_VER) || defined(__BORLANDC__)
23 # include "config_win32.h"
24 #else
25 # include "config.h"
26 #endif
27
28 #ifdef WIN32
29 # define SHIBMYSQL_EXPORTS __declspec(dllexport)
30 #else
31 # define SHIBMYSQL_EXPORTS
32 #endif
33
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #include <shib-target/shib-target.h>
39 #include <shib/shib-threads.h>
40 #include <log4cpp/Category.hh>
41
42 #include <sstream>
43 #include <stdexcept>
44
45 #include <mysql.h>
46
47 #ifdef HAVE_LIBDMALLOCXX
48 #include <dmalloc.h>
49 #endif
50
51 using namespace std;
52 using namespace saml;
53 using namespace shibboleth;
54 using namespace shibtarget;
55
56 #define PLUGIN_VER_MAJOR 1
57 #define PLUGIN_VER_MINOR 0
58
59 static const XMLCh Argument[] =
60 { chLatin_A, chLatin_r, chLatin_g, chLatin_u, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };
61 static const XMLCh cleanupInterval[] =
62 { chLatin_c, chLatin_l, chLatin_e, chLatin_a, chLatin_n, chLatin_u, chLatin_p,
63   chLatin_I, chLatin_n, chLatin_t, chLatin_e, chLatin_r, chLatin_v, chLatin_a, chLatin_l, chNull
64 };
65 static const XMLCh cacheTimeout[] =
66 { 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 };
67 static const XMLCh mysqlTimeout[] =
68 { 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 };
69
70 class ShibMySQLCCache;
71 class ShibMySQLCCacheEntry : public ISessionCacheEntry
72 {
73 public:
74   ShibMySQLCCacheEntry(const char*, ISessionCacheEntry*, ShibMySQLCCache*);
75   ~ShibMySQLCCacheEntry() {}
76
77   virtual void lock() {}
78   virtual void unlock() { m_cacheEntry->unlock(); delete this; }
79   virtual bool isValid(time_t lifetime, time_t timeout) const;
80   virtual const char* getClientAddress() const { return m_cacheEntry->getClientAddress(); }
81   virtual const char* getSerializedStatement() const { return m_cacheEntry->getSerializedStatement(); }
82   virtual const SAMLAuthenticationStatement* getStatement() const { return m_cacheEntry->getStatement(); }
83   virtual Iterator<SAMLAssertion*> getAssertions() { return m_cacheEntry->getAssertions(); }
84   virtual void preFetch(int prefetch_window) { m_cacheEntry->preFetch(prefetch_window); }
85
86 private:
87   bool touch() const;
88
89   ShibMySQLCCache* m_cache;
90   ISessionCacheEntry* m_cacheEntry;
91   string m_key;
92 };
93
94 class ShibMySQLCCache : public ISessionCache
95 {
96 public:
97   ShibMySQLCCache(const DOMElement* e);
98   virtual ~ShibMySQLCCache();
99
100   virtual void thread_init();
101   virtual void thread_end() {}
102
103   virtual string generateKey() const {return m_cache->generateKey();}
104   virtual ISessionCacheEntry* find(const char* key);
105   virtual void insert(
106         const char* key,
107         const IApplication* application,
108         SAMLAuthenticationStatement *s,
109         const char *client_addr,
110         SAMLResponse* r=NULL);
111   virtual void remove(const char* key);
112
113   void  cleanup();
114   MYSQL* getMYSQL() const;
115
116   log4cpp::Category* log;
117
118 private:
119   ISessionCache* m_cache;
120   ThreadKey* m_mysql;
121   const DOMElement* m_root; // can only use this during initialization
122
123   static void*  cleanup_fcn(void*); // XXX Assumed an ShibMySQLCCache
124   CondWait* shutdown_wait;
125   bool shutdown;
126   Thread* cleanup_thread;
127
128   bool initialized;
129
130   void createDatabase(MYSQL*, int major, int minor);
131   void upgradeDatabase(MYSQL*);
132   void getVersion(MYSQL*, int* major_p, int* minor_p);
133   void mysqlInit(void);
134 };
135
136 // Forward declarations
137 extern "C" void shib_mysql_destroy_handle(void* data);
138
139 /*************************************************************************
140  * The CCache here talks to a MySQL database.  The database stores
141  * three items: the cookie (session key index), the lastAccess time, and
142  * the SAMLAuthenticationStatement.  All other access is performed
143  * through the memory cache provided by shibboleth.
144  */
145
146 MYSQL* ShibMySQLCCache::getMYSQL() const
147 {
148   void* data = m_mysql->getData();
149   return (MYSQL*)data;
150 }
151
152 void ShibMySQLCCache::thread_init()
153 {
154   saml::NDC ndc("thread_init");
155
156   // Connect to the database
157   MYSQL* mysql = mysql_init(NULL);
158   if (!mysql) {
159     log->error("mysql_init failed");
160     mysql_close(mysql);
161     throw runtime_error("mysql_init()");
162   }
163
164   if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
165     if (initialized) {
166       log->crit("mysql_real_connect failed: %s", mysql_error(mysql));
167       throw runtime_error("mysql_real_connect");
168
169     } else {
170       log->info("mysql_real_connect failed: %s.  Trying to create",
171                 mysql_error(mysql));
172
173       // This will throw a runtime error if it fails.
174       createDatabase(mysql, PLUGIN_VER_MAJOR, PLUGIN_VER_MINOR);
175     }
176   }
177
178   int major = -1, minor = -1;
179   getVersion (mysql, &major, &minor);
180
181   // Make sure we've got the right version
182   if (major != PLUGIN_VER_MAJOR || minor != PLUGIN_VER_MINOR) {
183    
184     // If we're capable, try upgrading on the fly...
185     if (major == 0 && minor == 0) {
186        upgradeDatabase(mysql);
187     }
188     else {
189         log->crit("Invalid database version: %d.%d", major, minor);
190         throw runtime_error("Invalid Database version");
191     }
192   }
193
194   // We're all set.. Save off the handle for this thread.
195   m_mysql->setData((void*)mysql);
196 }
197
198 ShibMySQLCCache::ShibMySQLCCache(const DOMElement* e)
199 {
200   saml::NDC ndc("shibmysql::ShibMySQLCCache");
201
202   m_mysql = ThreadKey::create(&shib_mysql_destroy_handle);
203   log = &(log4cpp::Category::getInstance("shibmysql::ShibMySQLCCache"));
204
205   m_root=e;
206   initialized = false;
207   mysqlInit();
208   thread_init();
209   initialized = true;
210
211   m_cache = dynamic_cast<ISessionCache*>(
212       ShibConfig::getConfig().m_plugMgr.newPlugin(
213         "edu.internet2.middleware.shibboleth.target.provider.MemoryCache", e
214         )
215     );
216
217   // Initialize the cleanup thread
218   shutdown_wait = CondWait::create();
219   shutdown = false;
220   cleanup_thread = Thread::create(&cleanup_fcn, (void*)this);
221 }
222
223 ShibMySQLCCache::~ShibMySQLCCache()
224 {
225   shutdown = true;
226   shutdown_wait->signal();
227   cleanup_thread->join(NULL);
228
229   delete m_cache;
230   delete m_mysql;
231
232   // Shutdown MySQL
233   mysql_server_end();
234 }
235
236 ISessionCacheEntry* ShibMySQLCCache::find(const char* key)
237 {
238   saml::NDC ndc("mysql::find");
239   ISessionCacheEntry* res = m_cache->find(key);
240   if (!res) {
241
242     log->debug("Looking in database...");
243
244     // nothing cached; see if this exists in the database
245     string q = string("SELECT application_id,addr,statement FROM state WHERE cookie='") + key + "' LIMIT 1";
246
247     MYSQL_RES* rows;
248     MYSQL* mysql = getMYSQL();
249     if (mysql_query(mysql, q.c_str()))
250       log->error("Error searching for %s: %s", key, mysql_error(mysql));
251
252     rows = mysql_store_result(mysql);
253
254     // Nope, doesn't exist.
255     if (!rows)
256       return NULL;
257
258     // Make sure we got 1 and only 1 rows.
259     if (mysql_num_rows(rows) != 1) {
260       log->error("Select returned wrong number of rows: %d", mysql_num_rows(rows));
261       mysql_free_result(rows);
262       return NULL;
263     }
264
265     log->debug("Match found.  Parsing...");
266
267     // Pull apart the row and process the results
268     MYSQL_ROW row = mysql_fetch_row(rows);
269     IConfig* conf=ShibTargetConfig::getConfig().getINI();
270     Locker locker(conf);
271     const IApplication* application=conf->getApplication(row[0]);
272     if (!application) {
273         mysql_free_result(rows);
274         throw ShibTargetException(SHIBRPC_INTERNAL_ERROR,"unable to locate application for session, deleted?");
275     }
276
277     istringstream str(row[2]);
278     SAMLAuthenticationStatement *s = NULL;
279
280     // Try to parse the AuthStatement
281     try {
282       s = new SAMLAuthenticationStatement(str);
283     } catch (...) {
284       mysql_free_result(rows);
285       throw;
286     }
287
288     // Insert it into the memory cache
289     if (s)
290       m_cache->insert(key, application, s, row[1]);
291
292     // Free the results, and then re-run the 'find' query
293     mysql_free_result(rows);
294     res = m_cache->find(key);
295     if (!res)
296       return NULL;
297   }
298
299   return new ShibMySQLCCacheEntry(key, res, this);
300 }
301
302 void ShibMySQLCCache::insert(
303     const char* key,
304     const IApplication* application,
305     saml::SAMLAuthenticationStatement *s,
306     const char *client_addr,
307     saml::SAMLResponse* r)
308 {
309   saml::NDC ndc("mysql::insert");
310   ostringstream os;
311   os << *s;
312
313   string q = string("INSERT INTO state VALUES('") + key + "','" + application->getId() + "',NOW(),'" + client_addr + "','" + os.str() + "')";
314
315   log->debug("Query: %s", q.c_str());
316
317   // Add it to the memory cache
318   m_cache->insert(key, application, s, client_addr, r);
319
320   // then add it to the database
321   MYSQL* mysql = getMYSQL();
322   if (mysql_query(mysql, q.c_str()))
323     log->error("Error inserting %s: %s", key, mysql_error(mysql));
324 }
325
326 void ShibMySQLCCache::remove(const char* key)
327 {
328   saml::NDC ndc("mysql::remove");
329
330   // Remove the cached version
331   m_cache->remove(key);
332
333   // Remove from the database
334   string q = string("DELETE FROM state WHERE cookie='") + key + "'";
335   MYSQL* mysql = getMYSQL();
336   if (mysql_query(mysql, q.c_str()))
337     log->info("Error deleting entry %s: %s", key, mysql_error(mysql));
338 }
339
340 void ShibMySQLCCache::cleanup()
341 {
342   Mutex* mutex = Mutex::create();
343   saml::NDC ndc("mysql::cleanup");
344
345   thread_init();
346
347   int rerun_timer = 0;
348   int timeout_life = 0;
349
350   // Load our configuration details...
351   const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);
352   if (tag && *tag)
353     rerun_timer = XMLString::parseInt(tag);
354
355   // search for 'mysql-cache-timeout' and then the regular cache timeout
356   tag=m_root->getAttributeNS(NULL,mysqlTimeout);
357   if (tag && *tag)
358     timeout_life = XMLString::parseInt(tag);
359   else {
360       tag=m_root->getAttributeNS(NULL,cacheTimeout);
361       if (tag && *tag)
362         timeout_life = XMLString::parseInt(tag);
363   }
364   
365   if (rerun_timer <= 0)
366     rerun_timer = 300;          // rerun every 5 minutes
367
368   if (timeout_life <= 0)
369     timeout_life = 28800;       // timeout after 8 hours
370
371   mutex->lock();
372
373   MYSQL* mysql = getMYSQL();
374
375   while (shutdown == false) {
376     shutdown_wait->timedwait(mutex, rerun_timer);
377
378     if (shutdown == true)
379       break;
380
381     // Find all the entries in the database that haven't been used
382     // recently In particular, find all entries that have not been
383     // accessed in 'timeout_life' seconds.
384     ostringstream q;
385     q << "SELECT cookie FROM state WHERE " <<
386       "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(atime) >= " << timeout_life;
387
388     MYSQL_RES *rows;
389     if (mysql_query(mysql, q.str().c_str()))
390       log->error("Error searching for old items: %s", mysql_error(mysql));
391
392     rows = mysql_store_result(mysql);
393     if (!rows)
394       continue;
395
396     if (mysql_num_fields(rows) != 1) {
397       log->error("Wrong number of rows, 1 != %d", mysql_num_fields(rows));
398       mysql_free_result(rows);
399       continue;
400     }
401
402     // For each row, remove the entry from the database.
403     MYSQL_ROW row;
404     while ((row = mysql_fetch_row(rows)) != NULL)
405       remove(row[0]);
406
407     mysql_free_result(rows);
408   }
409
410   log->debug("cleanup thread exiting...");
411
412   mutex->unlock();
413   delete mutex;
414   thread_end();
415   Thread::exit(NULL);
416 }
417
418 void* ShibMySQLCCache::cleanup_fcn(void* cache_p)
419 {
420   ShibMySQLCCache* cache = (ShibMySQLCCache*)cache_p;
421
422   // First, let's block all signals
423   Thread::mask_all_signals();
424
425   // Now run the cleanup process.
426   cache->cleanup();
427   return NULL;
428 }
429
430 void ShibMySQLCCache::createDatabase(MYSQL* mysql, int major, int minor)
431 {
432   log->info("Creating database.");
433
434   MYSQL* ms = NULL;
435   try {
436     ms = mysql_init(NULL);
437     if (!ms) {
438       log->crit("mysql_init failed");
439       throw ShibTargetException();
440     }
441
442     if (!mysql_real_connect(ms, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
443       log->crit("cannot open DB file to create DB: %s", mysql_error(ms));
444       throw ShibTargetException();
445     }
446
447     if (mysql_query(ms, "CREATE DATABASE shar")) {
448       log->crit("cannot create shar database: %s", mysql_error(ms));
449       throw ShibTargetException();
450     }
451
452     if (!mysql_real_connect(mysql, NULL, NULL, NULL, "shar", 0, NULL, 0)) {
453       log->crit("cannot open SHAR database");
454       throw ShibTargetException();
455     }
456
457     mysql_close(ms);
458     
459   } catch (ShibTargetException&) {
460     if (ms)
461       mysql_close(ms);
462     mysql_close(mysql);
463     throw runtime_error("mysql_real_connect");
464   }
465
466   // Now create the tables if they don't exist
467   log->info("Creating database tables.");
468
469   if (mysql_query(mysql, "CREATE TABLE version (major INT, minor INT)"))
470     log->error ("Error creating version: %s", mysql_error(mysql));
471
472   if (mysql_query(mysql,
473                   "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, application_id VARCHAR(255),"
474                   "atime DATETIME, addr VARCHAR(128), statement TEXT)"))
475     log->error ("Error creating state: %s", mysql_error(mysql));
476
477   ostringstream q;
478   q << "INSERT INTO version VALUES(" << major << "," << minor << ")";
479   if (mysql_query(mysql, q.str().c_str()))
480     log->error ("Error setting version: %s", mysql_error(mysql));
481 }
482
483 void ShibMySQLCCache::upgradeDatabase(MYSQL* mysql)
484 {
485     if (mysql_query(mysql, "DROP TABLE state")) {
486         log->error("Error dropping old session state table: %s", mysql_error(mysql));
487     }
488
489     if (mysql_query(mysql,
490         "CREATE TABLE state (cookie VARCHAR(64) PRIMARY KEY, application_id VARCHAR(255),"
491        "atime DATETIME, addr VARCHAR(128), statement TEXT)")) {
492         log->error ("Error creating state table: %s", mysql_error(mysql));
493         throw runtime_error("error creating table");
494     }
495
496     ostringstream q;
497     q << "UPDATE version SET major = " << PLUGIN_VER_MAJOR;
498     if (mysql_query(mysql, q.str().c_str())) {
499         log->error ("Error updating version: %s", mysql_error(mysql));
500         throw runtime_error("error updating table");
501     }
502 }
503
504 void ShibMySQLCCache::getVersion(MYSQL* mysql, int* major_p, int* minor_p)
505 {
506   // grab the version number from the database
507   if (mysql_query(mysql, "SELECT * FROM version"))
508     log->error ("Error reading version: %s", mysql_error(mysql));
509
510   MYSQL_RES* rows = mysql_store_result(mysql);
511   if (rows) {
512     if (mysql_num_rows(rows) == 1 && mysql_num_fields(rows) == 2)  {
513       MYSQL_ROW row = mysql_fetch_row(rows);
514
515       int major = row[0] ? atoi(row[0]) : -1;
516       int minor = row[1] ? atoi(row[1]) : -1;
517       log->debug("opening database version %d.%d", major, minor);
518       
519       mysql_free_result (rows);
520
521       *major_p = major;
522       *minor_p = minor;
523       return;
524
525     } else {
526       // Wrong number of rows or wrong number of fields...
527
528       log->crit("Houston, we've got a problem with the database..");
529       mysql_free_result (rows);
530       throw runtime_error("Database version verification failed");
531     }
532   }
533   log->crit("MySQL Read Failed in version verificatoin");
534   throw runtime_error("MySQL Read Failed");
535 }
536
537 void ShibMySQLCCache::mysqlInit(void)
538 {
539   log->info ("Opening MySQL Database");
540
541   // Setup the argument array
542   vector<string> arg_array;
543   arg_array.push_back("shar");
544
545   // grab any MySQL parameters from the config file
546   const DOMElement* e=saml::XML::getFirstChildElement(m_root,ShibTargetConfig::SHIBTARGET_NS,Argument);
547   while (e) {
548       auto_ptr_char arg(e->getFirstChild()->getNodeValue());
549       if (arg.get())
550           arg_array.push_back(arg.get());
551       e=saml::XML::getNextSiblingElement(e,ShibTargetConfig::SHIBTARGET_NS,Argument);
552   }
553
554   // Compute the argument array
555   int arg_count = arg_array.size();
556   const char** args=new const char*[arg_count];
557   for (int i = 0; i < arg_count; i++)
558     args[i] = arg_array[i].c_str();
559
560   // Initialize MySQL with the arguments
561   mysql_server_init(arg_count, (char **)args, NULL);
562
563   delete[] args;
564 }  
565
566 /*************************************************************************
567  * The CCacheEntry here is mostly a wrapper around the "memory"
568  * cacheentry provided by shibboleth.  The only difference is that we
569  * intercept the isSessionValid() so that we can "touch()" the
570  * database if the session is still valid.
571  */
572
573 ShibMySQLCCacheEntry::ShibMySQLCCacheEntry(const char* key, ISessionCacheEntry* entry, ShibMySQLCCache* cache)
574 {
575   m_cacheEntry = entry;
576   m_key = key;
577   m_cache = cache;
578 }
579
580 bool ShibMySQLCCacheEntry::isValid(time_t lifetime, time_t timeout) const
581 {
582   bool res = m_cacheEntry->isValid(lifetime, timeout);
583   if (res == true)
584     res = touch();
585   return res;
586 }
587
588 bool ShibMySQLCCacheEntry::touch() const
589 {
590   string q=string("UPDATE state SET atime=NOW() WHERE cookie='") + m_key + "'";
591
592   MYSQL* mysql = m_cache->getMYSQL();
593   if (mysql_query(mysql, q.c_str())) {
594     m_cache->log->info("Error updating timestamp on %s: %s",
595                         m_key.c_str(), mysql_error(mysql));
596     return false;
597   }
598   return true;
599 }
600
601 /*************************************************************************
602  * The registration functions here...
603  */
604
605 IPlugIn* new_mysql_ccache(const DOMElement* e)
606 {
607   return new ShibMySQLCCache(e);
608 }
609
610 extern "C" int SHIBMYSQL_EXPORTS saml_extension_init(void*)
611 {
612   // register this ccache type
613   ShibConfig::getConfig().m_plugMgr.regFactory(
614     "edu.internet2.middleware.shibboleth.target.provider.MySQLSessionCache", &new_mysql_ccache
615     );
616   return 0;
617 }
618
619 /*************************************************************************
620  * Local Functions
621  */
622
623 extern "C" void shib_mysql_destroy_handle(void* data)
624 {
625   MYSQL* mysql = (MYSQL*) data;
626   mysql_close(mysql);
627 }