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