Use shibboleth-sp as package name for compatibility.
[shibboleth/cpp-sp.git] / odbc-store / odbc-store.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * odbc-store.cpp
23  *
24  * Storage Service using ODBC.
25  */
26
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
29 #else
30 # include "config.h"
31 #endif
32
33 #ifdef WIN32
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 #endif
37
38 #ifdef WIN32
39 # define ODBCSTORE_EXPORTS __declspec(dllexport)
40 #else
41 # define ODBCSTORE_EXPORTS
42 #endif
43
44 #include <xmltooling/logging.h>
45 #include <xmltooling/unicode.h>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/StorageService.h>
49 #include <xmltooling/util/Threads.h>
50 #include <xmltooling/util/XMLHelper.h>
51 #include <xercesc/util/XMLUniDefs.hpp>
52
53 #include <sql.h>
54 #include <sqlext.h>
55
56 #include <boost/lexical_cast.hpp>
57 #include <boost/algorithm/string.hpp>
58
59 using namespace xmltooling::logging;
60 using namespace xmltooling;
61 using namespace xercesc;
62 using namespace boost;
63 using namespace std;
64
65 #define PLUGIN_VER_MAJOR 1
66 #define PLUGIN_VER_MINOR 1
67
68 #define LONGDATA_BUFLEN 16384
69
70 #define COLSIZE_CONTEXT 255
71 #define COLSIZE_ID 255
72 #define COLSIZE_STRING_VALUE 255
73
74 #define STRING_TABLE "strings"
75 #define TEXT_TABLE "texts"
76
77 /* table definitions
78 CREATE TABLE version (
79     major int NOT nullptr,
80     minor int NOT nullptr
81     )
82
83 CREATE TABLE strings (
84     context varchar(255) not null,
85     id varchar(255) not null,
86     expires datetime not null,
87     version int not null,
88     value varchar(255) not null,
89     PRIMARY KEY (context, id)
90     )
91
92 CREATE TABLE texts (
93     context varchar(255) not null,
94     id varchar(255) not null,
95     expires datetime not null,
96     version int not null,
97     value text not null,
98     PRIMARY KEY (context, id)
99     )
100 */
101
102 namespace {
103     static const XMLCh cleanupInterval[] =  UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
104     static const XMLCh isolationLevel[] =   UNICODE_LITERAL_14(i,s,o,l,a,t,i,o,n,L,e,v,e,l);
105     static const XMLCh ConnectionString[] = UNICODE_LITERAL_16(C,o,n,n,e,c,t,i,o,n,S,t,r,i,n,g);
106     static const XMLCh RetryOnError[] =     UNICODE_LITERAL_12(R,e,t,r,y,O,n,E,r,r,o,r);
107     static const XMLCh contextSize[] =      UNICODE_LITERAL_11(c,o,n,t,e,x,t,S,i,z,e);
108     static const XMLCh keySize[] =          UNICODE_LITERAL_7(k,e,y,S,i,z,e);
109     static const XMLCh stringSize[] =       UNICODE_LITERAL_10(s,t,r,i,n,g,S,i,z,e);
110
111     // RAII for ODBC handles
112     struct ODBCConn {
113         ODBCConn(SQLHDBC conn) : handle(conn), autoCommit(true) {}
114         ~ODBCConn() {
115             if (handle != SQL_NULL_HDBC) {
116                 SQLRETURN sr = SQL_SUCCESS;
117                 if (!autoCommit)
118                     sr = SQLSetConnectAttr(handle, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON, 0);
119                 SQLDisconnect(handle);
120                 SQLFreeHandle(SQL_HANDLE_DBC, handle);
121                 if (!SQL_SUCCEEDED(sr))
122                     throw IOException("Failed to commit connection and return to auto-commit mode.");
123             }
124         }
125         operator SQLHDBC() {return handle;}
126         SQLHDBC handle;
127         bool autoCommit;
128     };
129
130     class ODBCStorageService : public StorageService
131     {
132     public:
133         ODBCStorageService(const DOMElement* e);
134         virtual ~ODBCStorageService();
135
136         const Capabilities& getCapabilities() const {
137             return m_caps;
138         }
139
140         bool createString(const char* context, const char* key, const char* value, time_t expiration) {
141             return createRow(STRING_TABLE, context, key, value, expiration);
142         }
143         int readString(const char* context, const char* key, string* pvalue=nullptr, time_t* pexpiration=nullptr, int version=0) {
144             return readRow(STRING_TABLE, context, key, pvalue, pexpiration, version);
145         }
146         int updateString(const char* context, const char* key, const char* value=nullptr, time_t expiration=0, int version=0) {
147             return updateRow(STRING_TABLE, context, key, value, expiration, version);
148         }
149         bool deleteString(const char* context, const char* key) {
150             return deleteRow(STRING_TABLE, context, key);
151         }
152
153         bool createText(const char* context, const char* key, const char* value, time_t expiration) {
154             return createRow(TEXT_TABLE, context, key, value, expiration);
155         }
156         int readText(const char* context, const char* key, string* pvalue=nullptr, time_t* pexpiration=nullptr, int version=0) {
157             return readRow(TEXT_TABLE, context, key, pvalue, pexpiration, version);
158         }
159         int updateText(const char* context, const char* key, const char* value=nullptr, time_t expiration=0, int version=0) {
160             return updateRow(TEXT_TABLE, context, key, value, expiration, version);
161         }
162         bool deleteText(const char* context, const char* key) {
163             return deleteRow(TEXT_TABLE, context, key);
164         }
165
166         void reap(const char* context) {
167             reap(STRING_TABLE, context);
168             reap(TEXT_TABLE, context);
169         }
170
171         void updateContext(const char* context, time_t expiration) {
172             updateContext(STRING_TABLE, context, expiration);
173             updateContext(TEXT_TABLE, context, expiration);
174         }
175
176         void deleteContext(const char* context) {
177             deleteContext(STRING_TABLE, context);
178             deleteContext(TEXT_TABLE, context);
179         }
180          
181
182     private:
183         bool createRow(const char *table, const char* context, const char* key, const char* value, time_t expiration);
184         int readRow(const char *table, const char* context, const char* key, string* pvalue, time_t* pexpiration, int version);
185         int updateRow(const char *table, const char* context, const char* key, const char* value, time_t expiration, int version);
186         bool deleteRow(const char *table, const char* context, const char* key);
187
188         void reap(const char* table, const char* context);
189         void updateContext(const char* table, const char* context, time_t expiration);
190         void deleteContext(const char* table, const char* context);
191
192         SQLHDBC getHDBC();
193         SQLHSTMT getHSTMT(SQLHDBC);
194         pair<SQLINTEGER,SQLINTEGER> getVersion(SQLHDBC);
195         pair<bool,bool> log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor=nullptr);
196
197         static void* cleanup_fn(void*); 
198         void cleanup();
199
200         Category& m_log;
201         Capabilities m_caps;
202         int m_cleanupInterval;
203         scoped_ptr<CondWait> shutdown_wait;
204         Thread* cleanup_thread;
205         bool shutdown;
206
207         SQLHENV m_henv;
208         string m_connstring;
209         long m_isolation;
210         bool m_wideVersion;
211         vector<SQLINTEGER> m_retries;
212     };
213
214     StorageService* ODBCStorageServiceFactory(const DOMElement* const & e)
215     {
216         return new ODBCStorageService(e);
217     }
218
219     // convert SQL timestamp to time_t 
220     time_t timeFromTimestamp(SQL_TIMESTAMP_STRUCT expires)
221     {
222         time_t ret;
223         struct tm t;
224         t.tm_sec=expires.second;
225         t.tm_min=expires.minute;
226         t.tm_hour=expires.hour;
227         t.tm_mday=expires.day;
228         t.tm_mon=expires.month-1;
229         t.tm_year=expires.year-1900;
230         t.tm_isdst=0;
231 #if defined(HAVE_TIMEGM)
232         ret = timegm(&t);
233 #else
234         ret = mktime(&t) - timezone;
235 #endif
236         return (ret);
237     }
238
239     // conver time_t to SQL string
240     void timestampFromTime(time_t t, char* ret)
241     {
242 #ifdef HAVE_GMTIME_R
243         struct tm res;
244         struct tm* ptime=gmtime_r(&t,&res);
245 #else
246         struct tm* ptime=gmtime(&t);
247 #endif
248         strftime(ret,32,"{ts '%Y-%m-%d %H:%M:%S'}",ptime);
249     }
250
251     class SQLString {
252         const char* m_src;
253         string m_copy;
254     public:
255         SQLString(const char* src) : m_src(src) {
256             if (strchr(src, '\'')) {
257                 m_copy = src;
258                 replace_all(m_copy, "'", "''");
259             }
260         }
261
262         operator const char*() const {
263             return tostr();
264         }
265
266         const char* tostr() const {
267             return m_copy.empty() ? m_src : m_copy.c_str();
268         }
269     };
270 };
271
272 ODBCStorageService::ODBCStorageService(const DOMElement* e) : m_log(Category::getInstance("XMLTooling.StorageService")),
273     m_caps(XMLHelper::getAttrInt(e, 255, contextSize), XMLHelper::getAttrInt(e, 255, keySize), XMLHelper::getAttrInt(e, 255, stringSize)),
274     m_cleanupInterval(XMLHelper::getAttrInt(e, 900, cleanupInterval)),
275     cleanup_thread(nullptr), shutdown(false), m_henv(SQL_NULL_HENV), m_isolation(SQL_TXN_SERIALIZABLE), m_wideVersion(false)
276 {
277 #ifdef _DEBUG
278     xmltooling::NDC ndc("ODBCStorageService");
279 #endif
280     string iso(XMLHelper::getAttrString(e, "SERIALIZABLE", isolationLevel));
281     if (iso == "SERIALIZABLE")
282         m_isolation = SQL_TXN_SERIALIZABLE;
283     else if (iso == "REPEATABLE_READ")
284         m_isolation = SQL_TXN_REPEATABLE_READ;
285     else if (iso == "READ_COMMITTED")
286         m_isolation = SQL_TXN_READ_COMMITTED;
287     else if (iso == "READ_UNCOMMITTED")
288         m_isolation = SQL_TXN_READ_UNCOMMITTED;
289     else
290         throw XMLToolingException("Unknown transaction isolationLevel property.");
291
292     if (m_henv == SQL_NULL_HENV) {
293         // Enable connection pooling.
294         SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, (void*)SQL_CP_ONE_PER_HENV, 0);
295
296         // Allocate the environment.
297         if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_henv)))
298             throw XMLToolingException("ODBC failed to initialize.");
299
300         // Specify ODBC 3.x
301         SQLSetEnvAttr(m_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
302
303         m_log.info("ODBC initialized");
304     }
305
306     // Grab connection string from the configuration.
307     e = e ? XMLHelper::getFirstChildElement(e, ConnectionString) : nullptr;
308     auto_ptr_char arg(e ? e->getTextContent() : nullptr);
309     if (!arg.get() || !*arg.get()) {
310         SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
311         throw XMLToolingException("ODBC StorageService requires ConnectionString element in configuration.");
312     }
313     m_connstring = arg.get();
314
315     // Connect and check version.
316     ODBCConn conn(getHDBC());
317     pair<SQLINTEGER,SQLINTEGER> v = getVersion(conn);
318
319     // Make sure we've got the right version.
320     if (v.first != PLUGIN_VER_MAJOR) {
321         SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
322         m_log.crit("unknown database version: %d.%d", v.first, v.second);
323         throw XMLToolingException("Unknown database version for ODBC StorageService.");
324     }
325     
326     if (v.first > 1 || v.second > 0) {
327         m_log.info("using 32-bit int type for version fields in tables");
328         m_wideVersion = true;
329     }
330
331     // Load any retry errors to check.
332     e = XMLHelper::getNextSiblingElement(e, RetryOnError);
333     while (e) {
334         if (e->hasChildNodes()) {
335             try {
336                 int code = XMLString::parseInt(e->getTextContent());
337                 m_retries.push_back(code);
338                 m_log.info("will retry operations when native ODBC error (%d) is returned", code);
339             }
340             catch (XMLException&) {
341                 m_log.error("skipping non-numeric ODBC retry code");
342             }
343         }
344         e = XMLHelper::getNextSiblingElement(e, RetryOnError);
345     }
346
347     if (m_cleanupInterval > 0) {
348         // Initialize the cleanup thread
349         shutdown_wait.reset(CondWait::create());
350         cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
351     }
352     else {
353         m_log.info("no cleanup interval configured, no cleanup thread will be started");
354     }
355 }
356
357 ODBCStorageService::~ODBCStorageService()
358 {
359     shutdown = true;
360     if (shutdown_wait.get()) {
361         shutdown_wait->signal();
362     }
363     if (cleanup_thread) {
364         cleanup_thread->join(nullptr);
365     }
366     if (m_henv != SQL_NULL_HANDLE) {
367         SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
368     }
369 }
370
371 pair<bool,bool> ODBCStorageService::log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor)
372 {
373     SQLSMALLINT  i = 0;
374     SQLINTEGER   native;
375     SQLCHAR      state[7];
376     SQLCHAR      text[256];
377     SQLSMALLINT  len;
378     SQLRETURN    ret;
379
380     pair<bool,bool> res = make_pair(false,false);
381     do {
382         ret = SQLGetDiagRec(htype, handle, ++i, state, &native, text, sizeof(text), &len);
383         if (SQL_SUCCEEDED(ret)) {
384             m_log.error("ODBC Error: %s:%ld:%ld:%s", state, i, native, text);
385             for (vector<SQLINTEGER>::const_iterator n = m_retries.begin(); !res.first && n != m_retries.end(); ++n)
386                 res.first = (*n == native);
387             if (checkfor && !strcmp(checkfor, (const char*)state))
388                 res.second = true;
389         }
390     } while(SQL_SUCCEEDED(ret));
391     return res;
392 }
393
394 SQLHDBC ODBCStorageService::getHDBC()
395 {
396 #ifdef _DEBUG
397     xmltooling::NDC ndc("getHDBC");
398 #endif
399
400     // Get a handle.
401     SQLHDBC handle = SQL_NULL_HDBC;
402     SQLRETURN sr = SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &handle);
403     if (!SQL_SUCCEEDED(sr) || handle == SQL_NULL_HDBC) {
404         m_log.error("failed to allocate connection handle");
405         log_error(m_henv, SQL_HANDLE_ENV);
406         throw IOException("ODBC StorageService failed to allocate a connection handle.");
407     }
408
409     sr = SQLDriverConnect(handle,nullptr,(SQLCHAR*)m_connstring.c_str(),m_connstring.length(),nullptr,0,nullptr,SQL_DRIVER_NOPROMPT);
410     if (!SQL_SUCCEEDED(sr)) {
411         m_log.error("failed to connect to database");
412         log_error(handle, SQL_HANDLE_DBC);
413         SQLFreeHandle(SQL_HANDLE_DBC, handle);
414         throw IOException("ODBC StorageService failed to connect to database.");
415     }
416
417     sr = SQLSetConnectAttr(handle, SQL_ATTR_TXN_ISOLATION, (SQLPOINTER)m_isolation, 0);
418     if (!SQL_SUCCEEDED(sr)) {
419         SQLDisconnect(handle);
420         SQLFreeHandle(SQL_HANDLE_DBC, handle);
421         throw IOException("ODBC StorageService failed to set transaction isolation level.");
422     }
423
424     return handle;
425 }
426
427 SQLHSTMT ODBCStorageService::getHSTMT(SQLHDBC conn)
428 {
429     SQLHSTMT hstmt = SQL_NULL_HSTMT;
430     SQLRETURN sr = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
431     if (!SQL_SUCCEEDED(sr) || hstmt == SQL_NULL_HSTMT) {
432         m_log.error("failed to allocate statement handle");
433         log_error(conn, SQL_HANDLE_DBC);
434         throw IOException("ODBC StorageService failed to allocate a statement handle.");
435     }
436     return hstmt;
437 }
438
439 pair<SQLINTEGER,SQLINTEGER> ODBCStorageService::getVersion(SQLHDBC conn)
440 {
441     // Grab the version number from the database.
442     SQLHSTMT stmt = getHSTMT(conn);
443     
444     SQLRETURN sr = SQLExecDirect(stmt, (SQLCHAR*)"SELECT major,minor FROM version", SQL_NTS);
445     if (!SQL_SUCCEEDED(sr)) {
446         m_log.error("failed to read version from database");
447         log_error(stmt, SQL_HANDLE_STMT);
448         throw IOException("ODBC StorageService failed to read version from database.");
449     }
450
451     SQLINTEGER major;
452     SQLINTEGER minor;
453     SQLBindCol(stmt, 1, SQL_C_SLONG, &major, 0, nullptr);
454     SQLBindCol(stmt, 2, SQL_C_SLONG, &minor, 0, nullptr);
455
456     if ((sr = SQLFetch(stmt)) != SQL_NO_DATA)
457         return make_pair(major,minor);
458
459     m_log.error("no rows returned in version query");
460     throw IOException("ODBC StorageService failed to read version from database.");
461 }
462
463 bool ODBCStorageService::createRow(const char* table, const char* context, const char* key, const char* value, time_t expiration)
464 {
465 #ifdef _DEBUG
466     xmltooling::NDC ndc("createRow");
467 #endif
468
469     char timebuf[32];
470     timestampFromTime(expiration, timebuf);
471
472     // Get statement handle.
473     ODBCConn conn(getHDBC());
474     SQLHSTMT stmt = getHSTMT(conn);
475
476     string q  = string("INSERT INTO ") + table + " VALUES (?,?," + timebuf + ",1,?)";
477
478     SQLRETURN sr = SQLPrepare(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
479     if (!SQL_SUCCEEDED(sr)) {
480         m_log.error("SQLPrepare failed (t=%s, c=%s, k=%s)", table, context, key);
481         log_error(stmt, SQL_HANDLE_STMT);
482         throw IOException("ODBC StorageService failed to insert record.");
483     }
484     m_log.debug("SQLPrepare succeeded. SQL: %s", q.c_str());
485
486     SQLLEN b_ind = SQL_NTS;
487     sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(context), &b_ind);
488     if (!SQL_SUCCEEDED(sr)) {
489         m_log.error("SQLBindParam failed (context = %s)", context);
490         log_error(stmt, SQL_HANDLE_STMT);
491         throw IOException("ODBC StorageService failed to insert record.");
492     }
493     m_log.debug("SQLBindParam succeeded (context = %s)", context);
494
495     sr = SQLBindParam(stmt, 2, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(key), &b_ind);
496     if (!SQL_SUCCEEDED(sr)) {
497         m_log.error("SQLBindParam failed (key = %s)", key);
498         log_error(stmt, SQL_HANDLE_STMT);
499         throw IOException("ODBC StorageService failed to insert record.");
500     }
501     m_log.debug("SQLBindParam succeeded (key = %s)", key);
502
503     if (strcmp(table, TEXT_TABLE)==0)
504         sr = SQLBindParam(stmt, 3, SQL_C_CHAR, SQL_LONGVARCHAR, strlen(value), 0, const_cast<char*>(value), &b_ind);
505     else
506         sr = SQLBindParam(stmt, 3, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(value), &b_ind);
507     if (!SQL_SUCCEEDED(sr)) {
508         m_log.error("SQLBindParam failed (value = %s)", value);
509         log_error(stmt, SQL_HANDLE_STMT);
510         throw IOException("ODBC StorageService failed to insert record.");
511     }
512     m_log.debug("SQLBindParam succeeded (value = %s)", value);
513     
514     int attempts = 3;
515     pair<bool,bool> logres;
516     do {
517         logres = make_pair(false,false);
518         attempts--;
519         sr = SQLExecute(stmt);
520         if (SQL_SUCCEEDED(sr)) {
521             m_log.debug("SQLExecute of insert succeeded");
522             return true;
523         }
524         m_log.error("insert record failed (t=%s, c=%s, k=%s)", table, context, key);
525         logres = log_error(stmt, SQL_HANDLE_STMT, "23000");
526         if (logres.second) {
527             // Supposedly integrity violation.
528             // Try and delete any expired record still hanging around until the final attempt.
529             if (attempts > 0) {
530                 reap(table, context);
531                 logres.first = true;    // force it to treat as a retryable error
532                 continue;
533             }
534             return false;
535         }
536     } while (attempts && logres.first);
537
538     throw IOException("ODBC StorageService failed to insert record.");
539 }
540
541 int ODBCStorageService::readRow(const char *table, const char* context, const char* key, string* pvalue, time_t* pexpiration, int version)
542 {
543 #ifdef _DEBUG
544     xmltooling::NDC ndc("readRow");
545 #endif
546
547     // Get statement handle.
548     ODBCConn conn(getHDBC());
549     SQLHSTMT stmt = getHSTMT(conn);
550
551     // Prepare and exectute select statement.
552     char timebuf[32];
553     timestampFromTime(time(nullptr), timebuf);
554     SQLString scontext(context);
555     SQLString skey(key);
556     string q("SELECT version");
557     if (pexpiration)
558         q += ",expires";
559     if (pvalue) {
560         pvalue->erase();
561         q = q + ",CASE version WHEN " + lexical_cast<string>(version) + " THEN null ELSE value END";
562     }
563     q = q + " FROM " + table + " WHERE context='" + scontext.tostr() + "' AND id='" + skey.tostr() + "' AND expires > " + timebuf;
564     if (m_log.isDebugEnabled())
565         m_log.debug("SQL: %s", q.c_str());
566
567     SQLRETURN sr=SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
568     if (!SQL_SUCCEEDED(sr)) {
569         m_log.error("error searching for (t=%s, c=%s, k=%s)", table, context, key);
570         log_error(stmt, SQL_HANDLE_STMT);
571         throw IOException("ODBC StorageService search failed.");
572     }
573
574     SQLSMALLINT ver;
575     SQLINTEGER widever;
576     SQL_TIMESTAMP_STRUCT expiration;
577
578     if (m_wideVersion)
579         SQLBindCol(stmt, 1, SQL_C_SLONG, &widever, 0, nullptr);
580     else
581         SQLBindCol(stmt, 1, SQL_C_SSHORT, &ver, 0, nullptr);
582     if (pexpiration)
583         SQLBindCol(stmt, 2, SQL_C_TYPE_TIMESTAMP, &expiration, 0, nullptr);
584
585     if ((sr = SQLFetch(stmt)) == SQL_NO_DATA) {
586         if (m_log.isDebugEnabled())
587             m_log.debug("search returned no data (t=%s, c=%s, k=%s)", table, context, key);
588         return 0;
589     }
590
591     if (pexpiration)
592         *pexpiration = timeFromTimestamp(expiration);
593
594     if (version == (m_wideVersion ? widever : ver)) {
595         if (m_log.isDebugEnabled())
596             m_log.debug("versioned search detected no change (t=%s, c=%s, k=%s)", table, context, key);
597         return version; // nothing's changed, so just echo back the version
598     }
599
600     if (pvalue) {
601         SQLLEN len;
602         SQLCHAR buf[LONGDATA_BUFLEN];
603         while ((sr = SQLGetData(stmt, (pexpiration ? 3 : 2), SQL_C_CHAR, buf, sizeof(buf), &len)) != SQL_NO_DATA) {
604             if (!SQL_SUCCEEDED(sr)) {
605                 m_log.error("error while reading text field from result set");
606                 log_error(stmt, SQL_HANDLE_STMT);
607                 throw IOException("ODBC StorageService search failed to read data from result set.");
608             }
609             pvalue->append((char*)buf);
610         }
611     }
612     
613     return (m_wideVersion ? widever : ver);
614 }
615
616 int ODBCStorageService::updateRow(const char *table, const char* context, const char* key, const char* value, time_t expiration, int version)
617 {
618 #ifdef _DEBUG
619     xmltooling::NDC ndc("updateRow");
620 #endif
621
622     if (!value && !expiration)
623         throw IOException("ODBC StorageService given invalid update instructions.");
624
625     // Get statement handle. Disable auto-commit mode to wrap select + update.
626     ODBCConn conn(getHDBC());
627     SQLRETURN sr = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);
628     if (!SQL_SUCCEEDED(sr))
629         throw IOException("ODBC StorageService failed to disable auto-commit mode.");
630     conn.autoCommit = false;
631     SQLHSTMT stmt = getHSTMT(conn);
632
633     // First, fetch the current version for later, which also ensures the record still exists.
634     char timebuf[32];
635     timestampFromTime(time(nullptr), timebuf);
636     SQLString scontext(context);
637     SQLString skey(key);
638     string q("SELECT version FROM ");
639     q = q + table + " WHERE context='" + scontext.tostr() + "' AND id='" + skey.tostr() + "' AND expires > " + timebuf;
640
641     m_log.debug("SQL: %s", q.c_str());
642
643     sr = SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
644     if (!SQL_SUCCEEDED(sr)) {
645         m_log.error("error searching for (t=%s, c=%s, k=%s)", table, context, key);
646         log_error(stmt, SQL_HANDLE_STMT);
647         throw IOException("ODBC StorageService search failed.");
648     }
649
650     SQLSMALLINT ver;
651     SQLINTEGER widever;
652     if (m_wideVersion)
653         SQLBindCol(stmt, 1, SQL_C_SLONG, &widever, 0, nullptr);
654     else
655         SQLBindCol(stmt, 1, SQL_C_SSHORT, &ver, 0, nullptr);
656     if ((sr = SQLFetch(stmt)) == SQL_NO_DATA) {
657         return 0;
658     }
659
660     // Check version?
661     if (version > 0 && version != (m_wideVersion ? widever : ver)) {
662         return -1;
663     }
664     else if ((m_wideVersion && widever == INT_MAX) || (!m_wideVersion && ver == 32767)) {
665         m_log.error("record version overflow (t=%s, c=%s, k=%s)", table, context, key);
666         throw IOException("Version overflow, record in ODBC StorageService could not be updated.");
667     }
668
669     SQLFreeHandle(SQL_HANDLE_STMT, stmt);
670     stmt = getHSTMT(conn);
671
672     // Prepare and exectute update statement.
673     q = string("UPDATE ") + table + " SET ";
674
675     if (value)
676         q = q + "value=?, version=version+1";
677
678     if (expiration) {
679         timestampFromTime(expiration, timebuf);
680         if (value)
681             q += ',';
682         q = q + "expires = " + timebuf;
683     }
684
685     q = q + " WHERE context='" + scontext.tostr() + "' AND id='" + skey.tostr() + "'";
686
687     sr = SQLPrepare(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
688     if (!SQL_SUCCEEDED(sr)) {
689         m_log.error("update of record failed (t=%s, c=%s, k=%s", table, context, key);
690         log_error(stmt, SQL_HANDLE_STMT);
691         throw IOException("ODBC StorageService failed to update record.");
692     }
693     m_log.debug("SQLPrepare succeeded. SQL: %s", q.c_str());
694
695     SQLLEN b_ind = SQL_NTS;
696     if (value) {
697         if (strcmp(table, TEXT_TABLE)==0)
698             sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_LONGVARCHAR, strlen(value), 0, const_cast<char*>(value), &b_ind);
699         else
700             sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(value), &b_ind);
701         if (!SQL_SUCCEEDED(sr)) {
702             m_log.error("SQLBindParam failed (value = %s)", value);
703             log_error(stmt, SQL_HANDLE_STMT);
704             throw IOException("ODBC StorageService failed to update record.");
705         }
706         m_log.debug("SQLBindParam succeeded (value = %s)", value);
707     }
708
709     int attempts = 3;
710     pair<bool,bool> logres;
711     do {
712         logres = make_pair(false,false);
713         attempts--;
714         sr = SQLExecute(stmt);
715         if (sr == SQL_NO_DATA)
716             return 0;   // went missing?
717         else if (SQL_SUCCEEDED(sr)) {
718             m_log.debug("SQLExecute of update succeeded");
719             return (m_wideVersion ? widever : ver) + 1;
720         }
721
722         m_log.error("update of record failed (t=%s, c=%s, k=%s)", table, context, key);
723         logres = log_error(stmt, SQL_HANDLE_STMT);
724     } while (attempts && logres.first);
725
726     throw IOException("ODBC StorageService failed to update record.");
727 }
728
729 bool ODBCStorageService::deleteRow(const char *table, const char *context, const char* key)
730 {
731 #ifdef _DEBUG
732     xmltooling::NDC ndc("deleteRow");
733 #endif
734
735     // Get statement handle.
736     ODBCConn conn(getHDBC());
737     SQLHSTMT stmt = getHSTMT(conn);
738
739     // Prepare and execute delete statement.
740     SQLString scontext(context);
741     SQLString skey(key);
742     string q = string("DELETE FROM ") + table + " WHERE context='" + scontext.tostr() + "' AND id='" + skey.tostr() + "'";
743     m_log.debug("SQL: %s", q.c_str());
744
745     SQLRETURN sr = SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
746      if (sr == SQL_NO_DATA)
747         return false;
748     else if (!SQL_SUCCEEDED(sr)) {
749         m_log.error("error deleting record (t=%s, c=%s, k=%s)", table, context, key);
750         log_error(stmt, SQL_HANDLE_STMT);
751         throw IOException("ODBC StorageService failed to delete record.");
752     }
753
754     return true;
755 }
756
757
758 void ODBCStorageService::cleanup()
759 {
760 #ifdef _DEBUG
761     xmltooling::NDC ndc("cleanup");
762 #endif
763
764     scoped_ptr<Mutex> mutex(Mutex::create());
765
766     mutex->lock();
767
768     m_log.info("cleanup thread started... running every %d secs", m_cleanupInterval);
769
770     while (!shutdown) {
771         shutdown_wait->timedwait(mutex.get(), m_cleanupInterval);
772         if (shutdown)
773             break;
774         try {
775             reap(nullptr);
776         }
777         catch (std::exception& ex) {
778             m_log.error("cleanup thread swallowed exception: %s", ex.what());
779         }
780     }
781
782     m_log.info("cleanup thread exiting...");
783
784     mutex->unlock();
785     Thread::exit(nullptr);
786 }
787
788 void* ODBCStorageService::cleanup_fn(void* cache_p)
789 {
790   ODBCStorageService* cache = (ODBCStorageService*)cache_p;
791
792 #ifndef WIN32
793   // First, let's block all signals
794   Thread::mask_all_signals();
795 #endif
796
797   // Now run the cleanup process.
798   cache->cleanup();
799   return nullptr;
800 }
801
802 void ODBCStorageService::updateContext(const char *table, const char* context, time_t expiration)
803 {
804 #ifdef _DEBUG
805     xmltooling::NDC ndc("updateContext");
806 #endif
807
808     // Get statement handle.
809     ODBCConn conn(getHDBC());
810     SQLHSTMT stmt = getHSTMT(conn);
811
812     char timebuf[32];
813     timestampFromTime(expiration, timebuf);
814
815     char nowbuf[32];
816     timestampFromTime(time(nullptr), nowbuf);
817
818     SQLString scontext(context);
819     string q = string("UPDATE ") + table + " SET expires = " + timebuf + " WHERE context='" + scontext.tostr() + "' AND expires > " + nowbuf;
820
821     m_log.debug("SQL: %s", q.c_str());
822
823     SQLRETURN sr = SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
824     if ((sr != SQL_NO_DATA) && !SQL_SUCCEEDED(sr)) {
825         m_log.error("error updating records (t=%s, c=%s)", table, context ? context : "all");
826         log_error(stmt, SQL_HANDLE_STMT);
827         throw IOException("ODBC StorageService failed to update context expiration.");
828     }
829 }
830
831 void ODBCStorageService::reap(const char *table, const char* context)
832 {
833 #ifdef _DEBUG
834     xmltooling::NDC ndc("reap");
835 #endif
836
837     // Get statement handle.
838     ODBCConn conn(getHDBC());
839     SQLHSTMT stmt = getHSTMT(conn);
840
841     // Prepare and execute delete statement.
842     char nowbuf[32];
843     timestampFromTime(time(nullptr), nowbuf);
844     string q;
845     if (context) {
846         SQLString scontext(context);
847         q = string("DELETE FROM ") + table + " WHERE context='" + scontext.tostr() + "' AND expires <= " + nowbuf;
848     }
849     else {
850         q = string("DELETE FROM ") + table + " WHERE expires <= " + nowbuf;
851     }
852     m_log.debug("SQL: %s", q.c_str());
853
854     SQLRETURN sr = SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
855     if ((sr != SQL_NO_DATA) && !SQL_SUCCEEDED(sr)) {
856         m_log.error("error expiring records (t=%s, c=%s)", table, context ? context : "all");
857         log_error(stmt, SQL_HANDLE_STMT);
858         throw IOException("ODBC StorageService failed to purge expired records.");
859     }
860 }
861
862 void ODBCStorageService::deleteContext(const char *table, const char* context)
863 {
864 #ifdef _DEBUG
865     xmltooling::NDC ndc("deleteContext");
866 #endif
867
868     // Get statement handle.
869     ODBCConn conn(getHDBC());
870     SQLHSTMT stmt = getHSTMT(conn);
871
872     // Prepare and execute delete statement.
873     SQLString scontext(context);
874     string q = string("DELETE FROM ") + table + " WHERE context='" + scontext.tostr() + "'";
875     m_log.debug("SQL: %s", q.c_str());
876
877     SQLRETURN sr = SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
878     if ((sr != SQL_NO_DATA) && !SQL_SUCCEEDED(sr)) {
879         m_log.error("error deleting context (t=%s, c=%s)", table, context);
880         log_error(stmt, SQL_HANDLE_STMT);
881         throw IOException("ODBC StorageService failed to delete context.");
882     }
883 }
884
885 extern "C" int ODBCSTORE_EXPORTS xmltooling_extension_init(void*)
886 {
887     // Register this SS type
888     XMLToolingConfig::getConfig().StorageServiceManager.registerFactory("ODBC", ODBCStorageServiceFactory);
889     return 0;
890 }
891
892 extern "C" void ODBCSTORE_EXPORTS xmltooling_extension_term()
893 {
894     XMLToolingConfig::getConfig().StorageServiceManager.deregisterFactory("ODBC");
895 }