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