Merge the realtime failover branch
[asterisk/asterisk.git] / res / res_config_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief odbc+odbc plugin for portable configuration engine
24  *
25  * \author Mark Spencer <markster@digium.com>
26  * \author Anthony Minessale II <anthmct@yahoo.com>
27  *
28  * \arg http://www.unixodbc.org
29  */
30
31 /*** MODULEINFO
32         <depend>res_odbc</depend>
33  ***/
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include "asterisk/file.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/config.h"
43 #include "asterisk/module.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/res_odbc.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/stringfields.h"
48
49 AST_THREADSTORAGE(sql_buf);
50
51 struct custom_prepare_struct {
52         const char *sql;
53         const char *extra;
54         AST_DECLARE_STRING_FIELDS(
55                 AST_STRING_FIELD(encoding)[256];
56         );
57         va_list ap;
58         unsigned long long skip;
59 };
60
61 static void decode_chunk(char *chunk)
62 {
63         for (; *chunk; chunk++) {
64                 if (*chunk == '^' && strchr("0123456789ABCDEFabcdef", chunk[1]) && strchr("0123456789ABCDEFabcdef", chunk[2])) {
65                         sscanf(chunk + 1, "%02hhd", chunk);
66                         memmove(chunk + 1, chunk + 3, strlen(chunk + 3) + 1);
67                 }
68         }
69 }
70
71 static SQLHSTMT custom_prepare(struct odbc_obj *obj, void *data)
72 {
73         int res, x = 1, count = 0;
74         struct custom_prepare_struct *cps = data;
75         const char *newparam, *newval;
76         char encodebuf[1024];
77         SQLHSTMT stmt;
78         va_list ap;
79
80         va_copy(ap, cps->ap);
81
82         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
83         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
84                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
85                 return NULL;
86         }
87
88         ast_debug(1, "Skip: %lld; SQL: %s\n", cps->skip, cps->sql);
89
90         res = SQLPrepare(stmt, (unsigned char *)cps->sql, SQL_NTS);
91         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
92                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", cps->sql);
93                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
94                 return NULL;
95         }
96
97         while ((newparam = va_arg(ap, const char *))) {
98                 newval = va_arg(ap, const char *);
99                 if ((1LL << count++) & cps->skip) {
100                         ast_debug(1, "Skipping field '%s'='%s' (%llo/%llo)\n", newparam, newval, 1LL << (count - 1), cps->skip);
101                         continue;
102                 }
103                 ast_debug(1, "Parameter %d ('%s') = '%s'\n", x, newparam, newval);
104                 if (strchr(newval, ';') || strchr(newval, '^')) {
105                         char *eptr = encodebuf;
106                         const char *vptr = newval;
107                         for (; *vptr && eptr < encodebuf + sizeof(encodebuf); vptr++) {
108                                 if (strchr("^;", *vptr)) {
109                                         /* We use ^XX, instead of %XX because '%' is a special character in SQL */
110                                         snprintf(eptr, encodebuf + sizeof(encodebuf) - eptr, "^%02hhX", *vptr);
111                                         eptr += 3;
112                                         vptr++;
113                                 } else {
114                                         *eptr++ = *vptr++;
115                                 }
116                         }
117                         if (eptr < encodebuf + sizeof(encodebuf)) {
118                                 *eptr = '\0';
119                         } else {
120                                 encodebuf[sizeof(encodebuf) - 1] = '\0';
121                         }
122                         ast_string_field_set(cps, encoding[x], encodebuf);
123                         newval = cps->encoding[x];
124                 }
125                 SQLBindParameter(stmt, x++, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(newval), 0, (void *)newval, 0, NULL);
126         }
127         va_end(ap);
128
129         if (!ast_strlen_zero(cps->extra))
130                 SQLBindParameter(stmt, x++, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(cps->extra), 0, (void *)cps->extra, 0, NULL);
131         return stmt;
132 }
133
134 /*!
135  * \brief Excute an SQL query and return ast_variable list
136  * \param database
137  * \param table
138  * \param ap list containing one or more field/operator/value set.
139  *
140  * Select database and preform query on table, prepare the sql statement
141  * Sub-in the values to the prepared statement and execute it. Return results
142  * as a ast_variable list.
143  *
144  * \retval var on success
145  * \retval NULL on failure
146 */
147 static struct ast_variable *realtime_odbc(const char *database, const char *table, va_list ap)
148 {
149         struct odbc_obj *obj;
150         SQLHSTMT stmt;
151         char sql[1024];
152         char coltitle[256];
153         char rowdata[2048];
154         char *op;
155         const char *newparam, *newval;
156         char *stringp;
157         char *chunk;
158         SQLSMALLINT collen;
159         int res;
160         int x;
161         struct ast_variable *var=NULL, *prev=NULL;
162         SQLULEN colsize;
163         SQLSMALLINT colcount=0;
164         SQLSMALLINT datatype;
165         SQLSMALLINT decimaldigits;
166         SQLSMALLINT nullable;
167         SQLLEN indicator;
168         va_list aq;
169         struct custom_prepare_struct cps = { .sql = sql };
170         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
171
172         if (ast_string_field_init(&cps, 256)) {
173                 return NULL;
174         }
175         va_copy(cps.ap, ap);
176         va_copy(aq, ap);
177
178         if (!table) {
179                 ast_string_field_free_memory(&cps);
180                 return NULL;
181         }
182
183         obj = ast_odbc_request_obj2(database, connected_flag);
184
185         if (!obj) {
186                 ast_log(LOG_ERROR, "No database handle available with the name of '%s' (check res_odbc.conf)\n", database);
187                 ast_string_field_free_memory(&cps);
188                 return NULL;
189         }
190
191         newparam = va_arg(aq, const char *);
192         if (!newparam) {
193                 ast_odbc_release_obj(obj);
194                 ast_string_field_free_memory(&cps);
195                 return NULL;
196         }
197         newval = va_arg(aq, const char *);
198         op = !strchr(newparam, ' ') ? " =" : "";
199         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s ?%s", table, newparam, op,
200                 strcasestr(newparam, "LIKE") && !ast_odbc_backslash_is_escape(obj) ? " ESCAPE '\\'" : "");
201         while((newparam = va_arg(aq, const char *))) {
202                 op = !strchr(newparam, ' ') ? " =" : "";
203                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s ?%s", newparam, op,
204                         strcasestr(newparam, "LIKE") && !ast_odbc_backslash_is_escape(obj) ? " ESCAPE '\\'" : "");
205                 newval = va_arg(aq, const char *);
206         }
207         va_end(aq);
208
209         stmt = ast_odbc_prepare_and_execute(obj, custom_prepare, &cps);
210
211         if (!stmt) {
212                 ast_odbc_release_obj(obj);
213                 ast_string_field_free_memory(&cps);
214                 return NULL;
215         }
216
217         res = SQLNumResultCols(stmt, &colcount);
218         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
219                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
220                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
221                 ast_odbc_release_obj(obj);
222                 ast_string_field_free_memory(&cps);
223                 return NULL;
224         }
225
226         res = SQLFetch(stmt);
227         if (res == SQL_NO_DATA) {
228                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
229                 ast_odbc_release_obj(obj);
230                 ast_string_field_free_memory(&cps);
231                 return NULL;
232         }
233         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
234                 ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
235                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
236                 ast_odbc_release_obj(obj);
237                 ast_string_field_free_memory(&cps);
238                 return NULL;
239         }
240         for (x = 0; x < colcount; x++) {
241                 rowdata[0] = '\0';
242                 collen = sizeof(coltitle);
243                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)coltitle, sizeof(coltitle), &collen, 
244                                         &datatype, &colsize, &decimaldigits, &nullable);
245                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
246                         ast_log(LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
247                         if (var)
248                                 ast_variables_destroy(var);
249                         ast_odbc_release_obj(obj);
250                         ast_string_field_free_memory(&cps);
251                         return NULL;
252                 }
253
254                 indicator = 0;
255                 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), &indicator);
256                 if (indicator == SQL_NULL_DATA)
257                         rowdata[0] = '\0';
258                 else if (ast_strlen_zero(rowdata)) {
259                         /* Because we encode the empty string for a NULL, we will encode
260                          * actual empty strings as a string containing a single whitespace. */
261                         ast_copy_string(rowdata, " ", sizeof(rowdata));
262                 }
263
264                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
265                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
266                         if (var)
267                                 ast_variables_destroy(var);
268                         ast_odbc_release_obj(obj);
269                         return NULL;
270                 }
271                 stringp = rowdata;
272                 while (stringp) {
273                         chunk = strsep(&stringp, ";");
274                         if (!ast_strlen_zero(ast_strip(chunk))) {
275                                 if (strchr(chunk, '^')) {
276                                         decode_chunk(chunk);
277                                 }
278                                 if (prev) {
279                                         prev->next = ast_variable_new(coltitle, chunk, "");
280                                         if (prev->next) {
281                                                 prev = prev->next;
282                                         }
283                                 } else {
284                                         prev = var = ast_variable_new(coltitle, chunk, "");
285                                 }
286                         }
287                 }
288         }
289
290
291         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
292         ast_odbc_release_obj(obj);
293         ast_string_field_free_memory(&cps);
294         return var;
295 }
296
297 /*!
298  * \brief Excute an Select query and return ast_config list
299  * \param database
300  * \param table
301  * \param ap list containing one or more field/operator/value set.
302  *
303  * Select database and preform query on table, prepare the sql statement
304  * Sub-in the values to the prepared statement and execute it. 
305  * Execute this prepared query against several ODBC connected databases.
306  * Return results as an ast_config variable.
307  *
308  * \retval var on success
309  * \retval NULL on failure
310 */
311 static struct ast_config *realtime_multi_odbc(const char *database, const char *table, va_list ap)
312 {
313         struct odbc_obj *obj;
314         SQLHSTMT stmt;
315         char sql[1024];
316         char coltitle[256];
317         char rowdata[2048];
318         const char *initfield=NULL;
319         char *op;
320         const char *newparam, *newval;
321         char *stringp;
322         char *chunk;
323         SQLSMALLINT collen;
324         int res;
325         int x;
326         struct ast_variable *var=NULL;
327         struct ast_config *cfg=NULL;
328         struct ast_category *cat=NULL;
329         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
330         SQLULEN colsize;
331         SQLSMALLINT colcount=0;
332         SQLSMALLINT datatype;
333         SQLSMALLINT decimaldigits;
334         SQLSMALLINT nullable;
335         SQLLEN indicator;
336         struct custom_prepare_struct cps = { .sql = sql };
337         va_list aq;
338
339         if (!table || ast_string_field_init(&cps, 256)) {
340                 return NULL;
341         }
342         va_copy(cps.ap, ap);
343         va_copy(aq, ap);
344
345
346         obj = ast_odbc_request_obj2(database, connected_flag);
347         if (!obj) {
348                 ast_string_field_free_memory(&cps);
349                 return NULL;
350         }
351
352         newparam = va_arg(aq, const char *);
353         if (!newparam)  {
354                 ast_odbc_release_obj(obj);
355                 ast_string_field_free_memory(&cps);
356                 return NULL;
357         }
358         initfield = ast_strdupa(newparam);
359         if ((op = strchr(initfield, ' '))) 
360                 *op = '\0';
361         newval = va_arg(aq, const char *);
362         op = !strchr(newparam, ' ') ? " =" : "";
363         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s ?%s", table, newparam, op,
364                 strcasestr(newparam, "LIKE") && !ast_odbc_backslash_is_escape(obj) ? " ESCAPE '\\'" : "");
365         while((newparam = va_arg(aq, const char *))) {
366                 op = !strchr(newparam, ' ') ? " =" : "";
367                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s ?%s", newparam, op,
368                         strcasestr(newparam, "LIKE") && !ast_odbc_backslash_is_escape(obj) ? " ESCAPE '\\'" : "");
369                 newval = va_arg(aq, const char *);
370         }
371         if (initfield)
372                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " ORDER BY %s", initfield);
373         va_end(aq);
374
375         stmt = ast_odbc_prepare_and_execute(obj, custom_prepare, &cps);
376
377         if (!stmt) {
378                 ast_odbc_release_obj(obj);
379                 ast_string_field_free_memory(&cps);
380                 return NULL;
381         }
382
383         res = SQLNumResultCols(stmt, &colcount);
384         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
385                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
386                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
387                 ast_odbc_release_obj(obj);
388                 ast_string_field_free_memory(&cps);
389                 return NULL;
390         }
391
392         cfg = ast_config_new();
393         if (!cfg) {
394                 ast_log(LOG_WARNING, "Out of memory!\n");
395                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
396                 ast_odbc_release_obj(obj);
397                 ast_string_field_free_memory(&cps);
398                 return NULL;
399         }
400
401         while ((res=SQLFetch(stmt)) != SQL_NO_DATA) {
402                 var = NULL;
403                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
404                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
405                         continue;
406                 }
407                 cat = ast_category_new("","",99999);
408                 if (!cat) {
409                         ast_log(LOG_WARNING, "Out of memory!\n");
410                         continue;
411                 }
412                 for (x=0;x<colcount;x++) {
413                         rowdata[0] = '\0';
414                         collen = sizeof(coltitle);
415                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)coltitle, sizeof(coltitle), &collen, 
416                                                 &datatype, &colsize, &decimaldigits, &nullable);
417                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
418                                 ast_log(LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
419                                 ast_category_destroy(cat);
420                                 continue;
421                         }
422
423                         indicator = 0;
424                         res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), &indicator);
425                         if (indicator == SQL_NULL_DATA)
426                                 continue;
427
428                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
429                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
430                                 ast_category_destroy(cat);
431                                 continue;
432                         }
433                         stringp = rowdata;
434                         while (stringp) {
435                                 chunk = strsep(&stringp, ";");
436                                 if (!ast_strlen_zero(ast_strip(chunk))) {
437                                         if (strchr(chunk, '^')) {
438                                                 decode_chunk(chunk);
439                                         }
440                                         if (initfield && !strcmp(initfield, coltitle)) {
441                                                 ast_category_rename(cat, chunk);
442                                         }
443                                         var = ast_variable_new(coltitle, chunk, "");
444                                         ast_variable_append(cat, var);
445                                 }
446                         }
447                 }
448                 ast_category_append(cfg, cat);
449         }
450
451         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
452         ast_odbc_release_obj(obj);
453         ast_string_field_free_memory(&cps);
454         return cfg;
455 }
456
457 /*!
458  * \brief Excute an UPDATE query
459  * \param database
460  * \param table
461  * \param keyfield where clause field
462  * \param lookup value of field for where clause
463  * \param ap list containing one or more field/value set(s).
464  *
465  * Update a database table, prepare the sql statement using keyfield and lookup
466  * control the number of records to change. All values to be changed are stored in ap list.
467  * Sub-in the values to the prepared statement and execute it.
468  *
469  * \retval number of rows affected
470  * \retval -1 on failure
471 */
472 static int update_odbc(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
473 {
474         struct odbc_obj *obj;
475         SQLHSTMT stmt;
476         char sql[256];
477         SQLLEN rowcount=0;
478         const char *newparam, *newval;
479         int res, count = 1;
480         va_list aq;
481         struct custom_prepare_struct cps = { .sql = sql, .extra = lookup };
482         struct odbc_cache_tables *tableptr;
483         struct odbc_cache_columns *column;
484         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
485
486         if (!table) {
487                 return -1;
488         }
489
490         va_copy(cps.ap, ap);
491         va_copy(aq, ap);
492
493         if (ast_string_field_init(&cps, 256)) {
494                 return -1;
495         }
496
497         tableptr = ast_odbc_find_table(database, table);
498         if (!(obj = ast_odbc_request_obj2(database, connected_flag))) {
499                 ast_odbc_release_table(tableptr);
500                 ast_string_field_free_memory(&cps);
501                 return -1;
502         }
503
504         newparam = va_arg(aq, const char *);
505         if (!newparam)  {
506                 ast_odbc_release_obj(obj);
507                 ast_odbc_release_table(tableptr);
508                 ast_string_field_free_memory(&cps);
509                 return -1;
510         }
511         newval = va_arg(aq, const char *);
512
513         if (tableptr && !(column = ast_odbc_find_column(tableptr, newparam))) {
514                 ast_log(LOG_WARNING, "Key field '%s' does not exist in table '%s@%s'.  Update will fail\n", newparam, table, database);
515         }
516
517         snprintf(sql, sizeof(sql), "UPDATE %s SET %s=?", table, newparam);
518         while((newparam = va_arg(aq, const char *))) {
519                 newval = va_arg(aq, const char *);
520                 if ((tableptr && (column = ast_odbc_find_column(tableptr, newparam))) || count > 63) {
521                         snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ", %s=?", newparam);
522                 } else { /* the column does not exist in the table */
523                         cps.skip |= (1LL << count);
524                 }
525                 count++;
526         }
527         va_end(aq);
528         snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " WHERE %s=?", keyfield);
529         ast_odbc_release_table(tableptr);
530
531         stmt = ast_odbc_prepare_and_execute(obj, custom_prepare, &cps);
532
533         if (!stmt) {
534                 ast_odbc_release_obj(obj);
535                 ast_string_field_free_memory(&cps);
536                 return -1;
537         }
538
539         res = SQLRowCount(stmt, &rowcount);
540         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
541         ast_odbc_release_obj(obj);
542         ast_string_field_free_memory(&cps);
543
544         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
545                 ast_log(LOG_WARNING, "SQL Row Count error!\n[%s]\n\n", sql);
546                 return -1;
547         }
548
549         if (rowcount >= 0) {
550                 return (int) rowcount;
551         }
552
553         return -1;
554 }
555
556 struct update2_prepare_struct {
557         const char *database;
558         const char *table;
559         va_list ap;
560 };
561
562 static SQLHSTMT update2_prepare(struct odbc_obj *obj, void *data)
563 {
564         int res, x = 1, first = 1;
565         struct update2_prepare_struct *ups = data;
566         const char *newparam, *newval;
567         struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
568         SQLHSTMT stmt;
569         va_list ap;
570         struct odbc_cache_tables *tableptr = ast_odbc_find_table(ups->database, ups->table);
571         struct odbc_cache_columns *column;
572
573         if (!sql) {
574                 if (tableptr) {
575                         ast_odbc_release_table(tableptr);
576                 }
577                 return NULL;
578         }
579
580         if (!tableptr) {
581                 ast_log(LOG_ERROR, "Could not retrieve metadata for table '%s@%s'.  Update will fail!\n", ups->table, ups->database);
582                 return NULL;
583         }
584
585         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
586         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
587                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
588                 ast_odbc_release_table(tableptr);
589                 return NULL;
590         }
591
592         ast_str_set(&sql, 0, "UPDATE %s SET ", ups->table);
593
594         /* Start by finding the second set of parameters */
595         va_copy(ap, ups->ap);
596
597         while ((newparam = va_arg(ap, const char *))) {
598                 newval = va_arg(ap, const char *);
599         }
600
601         while ((newparam = va_arg(ap, const char *))) {
602                 newval = va_arg(ap, const char *);
603                 if ((column = ast_odbc_find_column(tableptr, newparam))) {
604                         ast_str_append(&sql, 0, "%s%s=? ", first ? "" : ", ", newparam);
605                         SQLBindParameter(stmt, x++, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(newval), 0, (void *)newval, 0, NULL);
606                         first = 0;
607                 } else {
608                         ast_log(LOG_NOTICE, "Not updating column '%s' in '%s@%s' because that column does not exist!\n", newparam, ups->table, ups->database);
609                 }
610         }
611         va_end(ap);
612
613         /* Restart search, because we need to add the search parameters */
614         va_copy(ap, ups->ap);
615         ast_str_append(&sql, 0, "WHERE");
616         first = 1;
617
618         while ((newparam = va_arg(ap, const char *))) {
619                 newval = va_arg(ap, const char *);
620                 if (!(column = ast_odbc_find_column(tableptr, newparam))) {
621                         ast_log(LOG_ERROR, "One or more of the criteria columns '%s' on '%s@%s' for this update does not exist!\n", newparam, ups->table, ups->database);
622                         ast_odbc_release_table(tableptr);
623                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
624                         return NULL;
625                 }
626                 ast_str_append(&sql, 0, "%s %s=?", first ? "" : " AND", newparam);
627                 SQLBindParameter(stmt, x++, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(newval), 0, (void *)newval, 0, NULL);
628                 first = 0;
629         }
630         va_end(ap);
631
632         /* Done with the table metadata */
633         ast_odbc_release_table(tableptr);
634
635         res = SQLPrepare(stmt, (unsigned char *)ast_str_buffer(sql), SQL_NTS);
636         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
637                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", ast_str_buffer(sql));
638                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
639                 return NULL;
640         }
641
642         return stmt;
643 }
644
645 /*!
646  * \brief Execute an UPDATE query
647  * \param database
648  * \param table
649  * \param ap list containing one or more field/value set(s).
650  *
651  * Update a database table, preparing the sql statement from a list of
652  * key/value pairs specified in ap.  The lookup pairs are specified first
653  * and are separated from the update pairs by a sentinel value.
654  * Sub-in the values to the prepared statement and execute it.
655  *
656  * \retval number of rows affected
657  * \retval -1 on failure
658 */
659 static int update2_odbc(const char *database, const char *table, va_list ap)
660 {
661         struct odbc_obj *obj;
662         SQLHSTMT stmt;
663         struct update2_prepare_struct ups = { .database = database, .table = table, };
664         struct ast_str *sql;
665         int res;
666         SQLLEN rowcount = 0;
667
668         va_copy(ups.ap, ap);
669
670         if (!(obj = ast_odbc_request_obj(database, 0))) {
671                 return -1;
672         }
673
674         if (!(stmt = ast_odbc_prepare_and_execute(obj, update2_prepare, &ups))) {
675                 ast_odbc_release_obj(obj);
676                 return -1;
677         }
678
679         res = SQLRowCount(stmt, &rowcount);
680         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
681         ast_odbc_release_obj(obj);
682
683         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
684                 /* Since only a single thread can access this memory, we can retrieve what would otherwise be lost. */
685                 sql = ast_str_thread_get(&sql_buf, 16);
686                 ast_log(LOG_WARNING, "SQL Row Count error!\n[%s]\n", ast_str_buffer(sql));
687                 return -1;
688         }
689
690         if (rowcount >= 0) {
691                 return (int)rowcount;
692         }
693
694         return -1;
695 }
696
697 /*!
698  * \brief Excute an INSERT query
699  * \param database
700  * \param table
701  * \param ap list containing one or more field/value set(s)
702  *
703  * Insert a new record into database table, prepare the sql statement.
704  * All values to be changed are stored in ap list.
705  * Sub-in the values to the prepared statement and execute it.
706  *
707  * \retval number of rows affected
708  * \retval -1 on failure
709 */
710 static int store_odbc(const char *database, const char *table, va_list ap)
711 {
712         struct odbc_obj *obj;
713         SQLHSTMT stmt;
714         char sql[256];
715         char keys[256];
716         char vals[256];
717         SQLLEN rowcount=0;
718         const char *newparam, *newval;
719         int res;
720         va_list aq;
721         struct custom_prepare_struct cps = { .sql = sql, .extra = NULL };
722         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
723
724         va_copy(cps.ap, ap);
725         va_copy(aq, ap);
726         
727         if (!table)
728                 return -1;
729
730         obj = ast_odbc_request_obj2(database, connected_flag);
731         if (!obj)
732                 return -1;
733
734         newparam = va_arg(aq, const char *);
735         if (!newparam)  {
736                 ast_odbc_release_obj(obj);
737                 return -1;
738         }
739         newval = va_arg(aq, const char *);
740         snprintf(keys, sizeof(keys), "%s", newparam);
741         ast_copy_string(vals, "?", sizeof(vals));
742         while ((newparam = va_arg(aq, const char *))) {
743                 snprintf(keys + strlen(keys), sizeof(keys) - strlen(keys), ", %s", newparam);
744                 snprintf(vals + strlen(vals), sizeof(vals) - strlen(vals), ", ?");
745                 newval = va_arg(aq, const char *);
746         }
747         va_end(aq);
748         snprintf(sql, sizeof(sql), "INSERT INTO %s (%s) VALUES (%s)", table, keys, vals);
749
750         stmt = ast_odbc_prepare_and_execute(obj, custom_prepare, &cps);
751
752         if (!stmt) {
753                 ast_odbc_release_obj(obj);
754                 return -1;
755         }
756
757         res = SQLRowCount(stmt, &rowcount);
758         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
759         ast_odbc_release_obj(obj);
760
761         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
762                 ast_log(LOG_WARNING, "SQL Row Count error!\n[%s]\n\n", sql);
763                 return -1;
764         }
765
766         if (rowcount >= 0)
767                 return (int)rowcount;
768
769         return -1;
770 }
771
772 /*!
773  * \brief Excute an DELETE query
774  * \param database
775  * \param table
776  * \param keyfield where clause field
777  * \param lookup value of field for where clause
778  * \param ap list containing one or more field/value set(s)
779  *
780  * Delete a row from a database table, prepare the sql statement using keyfield and lookup
781  * control the number of records to change. Additional params to match rows are stored in ap list.
782  * Sub-in the values to the prepared statement and execute it.
783  *
784  * \retval number of rows affected
785  * \retval -1 on failure
786 */
787 static int destroy_odbc(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
788 {
789         struct odbc_obj *obj;
790         SQLHSTMT stmt;
791         char sql[256];
792         SQLLEN rowcount=0;
793         const char *newparam, *newval;
794         int res;
795         va_list aq;
796         struct custom_prepare_struct cps = { .sql = sql, .extra = lookup };
797         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
798
799         va_copy(cps.ap, ap);
800         va_copy(aq, ap);
801         
802         if (!table)
803                 return -1;
804
805         obj = ast_odbc_request_obj2(database, connected_flag);
806         if (!obj)
807                 return -1;
808
809         snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE ", table);
810         while((newparam = va_arg(aq, const char *))) {
811                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "%s=? AND ", newparam);
812                 newval = va_arg(aq, const char *);
813         }
814         va_end(aq);
815         snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "%s=?", keyfield);
816
817         stmt = ast_odbc_prepare_and_execute(obj, custom_prepare, &cps);
818
819         if (!stmt) {
820                 ast_odbc_release_obj(obj);
821                 return -1;
822         }
823
824         res = SQLRowCount(stmt, &rowcount);
825         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
826         ast_odbc_release_obj(obj);
827
828         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
829                 ast_log(LOG_WARNING, "SQL Row Count error!\n[%s]\n\n", sql);
830                 return -1;
831         }
832
833         if (rowcount >= 0)
834                 return (int)rowcount;
835
836         return -1;
837 }
838
839
840 struct config_odbc_obj {
841         char *sql;
842         unsigned long cat_metric;
843         char category[128];
844         char var_name[128];
845         char var_val[1024]; /* changed from 128 to 1024 via bug 8251 */
846         SQLLEN err;
847 };
848
849 static SQLHSTMT config_odbc_prepare(struct odbc_obj *obj, void *data)
850 {
851         struct config_odbc_obj *q = data;
852         SQLHSTMT sth;
853         int res;
854
855         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &sth);
856         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
857                 ast_verb(4, "Failure in AllocStatement %d\n", res);
858                 return NULL;
859         }
860
861         res = SQLPrepare(sth, (unsigned char *)q->sql, SQL_NTS);
862         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
863                 ast_verb(4, "Error in PREPARE %d\n", res);
864                 SQLFreeHandle(SQL_HANDLE_STMT, sth);
865                 return NULL;
866         }
867
868         SQLBindCol(sth, 1, SQL_C_ULONG, &q->cat_metric, sizeof(q->cat_metric), &q->err);
869         SQLBindCol(sth, 2, SQL_C_CHAR, q->category, sizeof(q->category), &q->err);
870         SQLBindCol(sth, 3, SQL_C_CHAR, q->var_name, sizeof(q->var_name), &q->err);
871         SQLBindCol(sth, 4, SQL_C_CHAR, q->var_val, sizeof(q->var_val), &q->err);
872
873         return sth;
874 }
875
876 static struct ast_config *config_odbc(const char *database, const char *table, const char *file, struct ast_config *cfg, struct ast_flags flags, const char *sugg_incl, const char *who_asked)
877 {
878         struct ast_variable *new_v;
879         struct ast_category *cur_cat;
880         int res = 0;
881         struct odbc_obj *obj;
882         char sqlbuf[1024] = "";
883         char *sql = sqlbuf;
884         size_t sqlleft = sizeof(sqlbuf);
885         unsigned int last_cat_metric = 0;
886         SQLSMALLINT rowcount = 0;
887         SQLHSTMT stmt;
888         char last[128] = "";
889         struct config_odbc_obj q;
890         struct ast_flags loader_flags = { 0 };
891         struct ast_flags connected_flag = { RES_ODBC_CONNECTED };
892
893         memset(&q, 0, sizeof(q));
894
895         if (!file || !strcmp (file, "res_config_odbc.conf"))
896                 return NULL;            /* cant configure myself with myself ! */
897
898         obj = ast_odbc_request_obj2(database, connected_flag);
899         if (!obj)
900                 return NULL;
901
902         ast_build_string(&sql, &sqlleft, "SELECT cat_metric, category, var_name, var_val FROM %s ", table);
903         ast_build_string(&sql, &sqlleft, "WHERE filename='%s' AND commented=0 ", file);
904         ast_build_string(&sql, &sqlleft, "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ");
905         q.sql = sqlbuf;
906
907         stmt = ast_odbc_prepare_and_execute(obj, config_odbc_prepare, &q);
908
909         if (!stmt) {
910                 ast_log(LOG_WARNING, "SQL select error!\n[%s]\n\n", sql);
911                 ast_odbc_release_obj(obj);
912                 return NULL;
913         }
914
915         res = SQLNumResultCols(stmt, &rowcount);
916
917         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
918                 ast_log(LOG_WARNING, "SQL NumResultCols error!\n[%s]\n\n", sql);
919                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
920                 ast_odbc_release_obj(obj);
921                 return NULL;
922         }
923
924         if (!rowcount) {
925                 ast_log(LOG_NOTICE, "found nothing\n");
926                 ast_odbc_release_obj(obj);
927                 return cfg;
928         }
929
930         cur_cat = ast_config_get_current_category(cfg);
931
932         while ((res = SQLFetch(stmt)) != SQL_NO_DATA) {
933                 if (!strcmp (q.var_name, "#include")) {
934                         if (!ast_config_internal_load(q.var_val, cfg, loader_flags, "", who_asked)) {
935                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
936                                 ast_odbc_release_obj(obj);
937                                 return NULL;
938                         }
939                         continue;
940                 } 
941                 if (strcmp(last, q.category) || last_cat_metric != q.cat_metric) {
942                         cur_cat = ast_category_new(q.category, "", 99999);
943                         if (!cur_cat) {
944                                 ast_log(LOG_WARNING, "Out of memory!\n");
945                                 break;
946                         }
947                         strcpy(last, q.category);
948                         last_cat_metric = q.cat_metric;
949                         ast_category_append(cfg, cur_cat);
950                 }
951
952                 new_v = ast_variable_new(q.var_name, q.var_val, "");
953                 ast_variable_append(cur_cat, new_v);
954         }
955
956         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
957         ast_odbc_release_obj(obj);
958         return cfg;
959 }
960
961 #define warn_length(col, size)  ast_log(LOG_WARNING, "Realtime table %s@%s: column '%s' is not long enough to contain realtime data (needs %d)\n", table, database, col->name, size)
962 #define warn_type(col, type)    ast_log(LOG_WARNING, "Realtime table %s@%s: column '%s' is of the incorrect type (%d) to contain the required realtime data\n", table, database, col->name, col->type)
963
964 static int require_odbc(const char *database, const char *table, va_list ap)
965 {
966         struct odbc_cache_tables *tableptr = ast_odbc_find_table(database, table);
967         struct odbc_cache_columns *col;
968         char *elm;
969         int type, size;
970
971         if (!tableptr) {
972                 return -1;
973         }
974
975         while ((elm = va_arg(ap, char *))) {
976                 type = va_arg(ap, require_type);
977                 size = va_arg(ap, int);
978                 /* Check if the field matches the criteria */
979                 AST_RWLIST_TRAVERSE(&tableptr->columns, col, list) {
980                         if (strcmp(col->name, elm) == 0) {
981                                 /* Type check, first.  Some fields are more particular than others */
982                                 switch (col->type) {
983                                 case SQL_CHAR:
984                                 case SQL_VARCHAR:
985                                 case SQL_LONGVARCHAR:
986 #ifdef HAVE_ODBC_WCHAR
987                                 case SQL_WCHAR:
988                                 case SQL_WVARCHAR:
989                                 case SQL_WLONGVARCHAR:
990 #endif
991                                 case SQL_BINARY:
992                                 case SQL_VARBINARY:
993                                 case SQL_LONGVARBINARY:
994                                 case SQL_GUID:
995 #define CHECK_SIZE(n) \
996                                                 if (col->size < n) {      \
997                                                         warn_length(col, n);  \
998                                                 }                         \
999                                                 break;
1000                                         switch (type) {
1001                                         case RQ_UINTEGER1: CHECK_SIZE(3)  /*         255 */
1002                                         case RQ_INTEGER1:  CHECK_SIZE(4)  /*        -128 */
1003                                         case RQ_UINTEGER2: CHECK_SIZE(5)  /*       65535 */
1004                                         case RQ_INTEGER2:  CHECK_SIZE(6)  /*      -32768 */
1005                                         case RQ_UINTEGER3:                /*    16777215 */
1006                                         case RQ_INTEGER3:  CHECK_SIZE(8)  /*    -8388608 */
1007                                         case RQ_DATE:                     /*  2008-06-09 */
1008                                         case RQ_UINTEGER4: CHECK_SIZE(10) /*  4200000000 */
1009                                         case RQ_INTEGER4:  CHECK_SIZE(11) /* -2100000000 */
1010                                         case RQ_DATETIME:                 /* 2008-06-09 16:03:47 */
1011                                         case RQ_UINTEGER8: CHECK_SIZE(19) /* trust me    */
1012                                         case RQ_INTEGER8:  CHECK_SIZE(20) /* ditto       */
1013                                         case RQ_FLOAT:
1014                                         case RQ_CHAR:      CHECK_SIZE(size)
1015                                         }
1016 #undef CHECK_SIZE
1017                                         break;
1018                                 case SQL_TYPE_DATE:
1019                                         if (type != RQ_DATE) {
1020                                                 warn_type(col, type);
1021                                         }
1022                                         break;
1023                                 case SQL_TYPE_TIMESTAMP:
1024                                 case SQL_TIMESTAMP:
1025                                         if (type != RQ_DATE && type != RQ_DATETIME) {
1026                                                 warn_type(col, type);
1027                                         }
1028                                         break;
1029                                 case SQL_BIT:
1030                                         warn_length(col, size);
1031                                         break;
1032 #define WARN_TYPE_OR_LENGTH(n)  \
1033                                                 if (!ast_rq_is_int(type)) {  \
1034                                                         warn_type(col, type);    \
1035                                                 } else {                     \
1036                                                         warn_length(col, n);  \
1037                                                 }
1038                                 case SQL_TINYINT:
1039                                         if (type != RQ_UINTEGER1) {
1040                                                 WARN_TYPE_OR_LENGTH(size)
1041                                         }
1042                                         break;
1043                                 case SQL_C_STINYINT:
1044                                         if (type != RQ_INTEGER1) {
1045                                                 WARN_TYPE_OR_LENGTH(size)
1046                                         }
1047                                         break;
1048                                 case SQL_C_USHORT:
1049                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 && type != RQ_UINTEGER2) {
1050                                                 WARN_TYPE_OR_LENGTH(size)
1051                                         }
1052                                         break;
1053                                 case SQL_SMALLINT:
1054                                 case SQL_C_SSHORT:
1055                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 && type != RQ_INTEGER2) {
1056                                                 WARN_TYPE_OR_LENGTH(size)
1057                                         }
1058                                         break;
1059                                 case SQL_C_ULONG:
1060                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
1061                                                 type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
1062                                                 type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
1063                                                 type != RQ_INTEGER4) {
1064                                                 WARN_TYPE_OR_LENGTH(size)
1065                                         }
1066                                         break;
1067                                 case SQL_INTEGER:
1068                                 case SQL_C_SLONG:
1069                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
1070                                                 type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
1071                                                 type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
1072                                                 type != RQ_INTEGER4) {
1073                                                 WARN_TYPE_OR_LENGTH(size)
1074                                         }
1075                                         break;
1076                                 case SQL_C_UBIGINT:
1077                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
1078                                                 type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
1079                                                 type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
1080                                                 type != RQ_UINTEGER4 && type != RQ_INTEGER4 &&
1081                                                 type != RQ_INTEGER8) {
1082                                                 WARN_TYPE_OR_LENGTH(size)
1083                                         }
1084                                         break;
1085                                 case SQL_BIGINT:
1086                                 case SQL_C_SBIGINT:
1087                                         if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
1088                                                 type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
1089                                                 type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
1090                                                 type != RQ_UINTEGER4 && type != RQ_INTEGER4 &&
1091                                                 type != RQ_INTEGER8) {
1092                                                 WARN_TYPE_OR_LENGTH(size)
1093                                         }
1094                                         break;
1095 #undef WARN_TYPE_OR_LENGTH
1096                                 case SQL_NUMERIC:
1097                                 case SQL_DECIMAL:
1098                                 case SQL_FLOAT:
1099                                 case SQL_REAL:
1100                                 case SQL_DOUBLE:
1101                                         if (!ast_rq_is_int(type) && type != RQ_FLOAT) {
1102                                                 warn_type(col, type);
1103                                         }
1104                                         break;
1105                                 default:
1106                                         ast_log(LOG_WARNING, "Realtime table %s@%s: column type (%d) unrecognized for column '%s'\n", table, database, col->type, elm);
1107                                 }
1108                                 break;
1109                         }
1110                 }
1111                 if (!col) {
1112                         ast_log(LOG_WARNING, "Realtime table %s@%s requires column '%s', but that column does not exist!\n", table, database, elm);
1113                 }
1114         }
1115         va_end(ap);
1116         AST_RWLIST_UNLOCK(&tableptr->columns);
1117         return 0;
1118 }
1119 #undef warn_length
1120 #undef warn_type
1121
1122 static struct ast_config_engine odbc_engine = {
1123         .name = "odbc",
1124         .load_func = config_odbc,
1125         .realtime_func = realtime_odbc,
1126         .realtime_multi_func = realtime_multi_odbc,
1127         .store_func = store_odbc,
1128         .destroy_func = destroy_odbc,
1129         .update_func = update_odbc,
1130         .update2_func = update2_odbc,
1131         .require_func = require_odbc,
1132         .unload_func = ast_odbc_clear_cache,
1133 };
1134
1135 static int unload_module (void)
1136 {
1137         ast_config_engine_deregister(&odbc_engine);
1138
1139         ast_verb(1, "res_config_odbc unloaded.\n");
1140         return 0;
1141 }
1142
1143 static int load_module (void)
1144 {
1145         ast_config_engine_register(&odbc_engine);
1146         ast_verb(1, "res_config_odbc loaded.\n");
1147         return 0;
1148 }
1149
1150 static int reload_module(void)
1151 {
1152         return 0;
1153 }
1154
1155 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Realtime ODBC configuration",
1156                 .load = load_module,
1157                 .unload = unload_module,
1158                 .reload = reload_module,
1159                 .load_pri = AST_MODPRI_REALTIME_DRIVER,
1160                 );