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