f9272fe889149212ee8a0d720fef816af6eda0f5
[asterisk/asterisk.git] / funcs / func_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2005, 2006 Tilghman Lesher
5  *
6  * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  *
22  * \brief ODBC lookups
23  *
24  * \author Tilghman Lesher <func_odbc__200508@the-tilghman.com>
25  *
26  * \ingroup functions
27  */
28
29 /*** MODULEINFO
30         <depend>unixodbc</depend>
31         <depend>ltdl</depend>
32         <depend>res_odbc</depend>
33  ***/
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include <sys/types.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <string.h>
44 #include <errno.h>
45
46 #include "asterisk/module.h"
47 #include "asterisk/file.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/options.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/module.h"
53 #include "asterisk/config.h"
54 #include "asterisk/res_odbc.h"
55 #include "asterisk/app.h"
56
57 static char *config = "func_odbc.conf";
58
59 enum {
60         OPT_ESCAPECOMMAS =      (1 << 0),
61         OPT_MULTIROW     =      (1 << 1),
62 } odbc_option_flags;
63
64 struct acf_odbc_query {
65         AST_LIST_ENTRY(acf_odbc_query) list;
66         char readhandle[5][30];
67         char writehandle[5][30];
68         char sql_read[2048];
69         char sql_write[2048];
70         unsigned int flags;
71         int rowlimit;
72         struct ast_custom_function *acf;
73 };
74
75 static void odbc_datastore_free(void *data);
76
77 struct ast_datastore_info odbc_info = {
78         .type = "FUNC_ODBC",
79         .destroy = odbc_datastore_free,
80 };
81
82 /* For storing each result row */
83 struct odbc_datastore_row {
84         AST_LIST_ENTRY(odbc_datastore_row) list;
85         char data[0];
86 };
87
88 /* For storing each result set */
89 struct odbc_datastore {
90         AST_LIST_HEAD(, odbc_datastore_row);
91         char names[0];
92 };
93
94 AST_LIST_HEAD_STATIC(queries, acf_odbc_query);
95
96 static int resultcount = 0;
97
98 static void odbc_datastore_free(void *data)
99 {
100         struct odbc_datastore *result = data;
101         struct odbc_datastore_row *row;
102         AST_LIST_LOCK(result);
103         while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
104                 ast_free(row);
105         }
106         AST_LIST_UNLOCK(result);
107         AST_LIST_HEAD_DESTROY(result);
108         ast_free(result);
109 }
110
111 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
112 {
113         int res;
114         char *sql = data;
115         SQLHSTMT stmt;
116
117         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
118         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
119                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
120                 return NULL;
121         }
122
123         res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
124         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
125                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
126                 SQLCloseCursor(stmt);
127                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
128                 return NULL;
129         }
130
131         return stmt;
132 }
133
134 /*
135  * Master control routine
136  */
137 static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
138 {
139         struct odbc_obj *obj = NULL;
140         struct acf_odbc_query *query;
141         char *t, buf[2048]="", varname[15];
142         int i, dsn;
143         AST_DECLARE_APP_ARGS(values,
144                 AST_APP_ARG(field)[100];
145         );
146         AST_DECLARE_APP_ARGS(args,
147                 AST_APP_ARG(field)[100];
148         );
149         SQLHSTMT stmt = NULL;
150         SQLLEN rows=0;
151
152         AST_LIST_LOCK(&queries);
153         AST_LIST_TRAVERSE(&queries, query, list) {
154                 if (!strcmp(query->acf->name, cmd)) {
155                         break;
156                 }
157         }
158
159         if (!query) {
160                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
161                 AST_LIST_UNLOCK(&queries);
162                 return -1;
163         }
164
165         /* Parse our arguments */
166         t = value ? ast_strdupa(value) : "";
167
168         if (!s || !t) {
169                 ast_log(LOG_ERROR, "Out of memory\n");
170                 AST_LIST_UNLOCK(&queries);
171                 return -1;
172         }
173
174         AST_STANDARD_APP_ARGS(args, s);
175         for (i = 0; i < args.argc; i++) {
176                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
177                 pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
178         }
179
180         /* Parse values, just like arguments */
181         AST_STANDARD_APP_ARGS(values, t);
182         for (i = 0; i < values.argc; i++) {
183                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
184                 pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
185         }
186
187         /* Additionally set the value as a whole (but push an empty string if value is NULL) */
188         pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
189
190         pbx_substitute_variables_helper(chan, query->sql_write, buf, sizeof(buf) - 1);
191
192         /* Restore prior values */
193         for (i = 0; i < args.argc; i++) {
194                 snprintf(varname, sizeof(varname), "ARG%d", i + 1);
195                 pbx_builtin_setvar_helper(chan, varname, NULL);
196         }
197
198         for (i = 0; i < values.argc; i++) {
199                 snprintf(varname, sizeof(varname), "VAL%d", i + 1);
200                 pbx_builtin_setvar_helper(chan, varname, NULL);
201         }
202         pbx_builtin_setvar_helper(chan, "VALUE", NULL);
203
204         AST_LIST_UNLOCK(&queries);
205
206         for (dsn = 0; dsn < 5; dsn++) {
207                 if (!ast_strlen_zero(query->writehandle[dsn])) {
208                         obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
209                         if (obj)
210                                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, buf);
211                 }
212                 if (stmt)
213                         break;
214         }
215
216         if (stmt) {
217                 /* Rows affected */
218                 SQLRowCount(stmt, &rows);
219         }
220
221         /* Output the affected rows, for all cases.  In the event of failure, we
222          * flag this as -1 rows.  Note that this is different from 0 affected rows
223          * which would be the case if we succeeded in our query, but the values did
224          * not change. */
225         snprintf(varname, sizeof(varname), "%d", (int)rows);
226         pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
227
228         if (stmt) {
229                 SQLCloseCursor(stmt);
230                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
231         }
232         if (obj)
233                 ast_odbc_release_obj(obj);
234
235         return 0;
236 }
237
238 static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
239 {
240         struct odbc_obj *obj = NULL;
241         struct acf_odbc_query *query;
242         char sql[2048] = "", varname[15], colnames[2048] = "", rowcount[12] = "-1";
243         int res, x, y, buflen = 0, escapecommas, rowlimit = 1, dsn;
244         AST_DECLARE_APP_ARGS(args,
245                 AST_APP_ARG(field)[100];
246         );
247         SQLHSTMT stmt = NULL;
248         SQLSMALLINT colcount=0;
249         SQLLEN indicator;
250         SQLSMALLINT collength;
251         struct odbc_datastore *resultset = NULL;
252         struct odbc_datastore_row *row = NULL;
253
254         AST_LIST_LOCK(&queries);
255         AST_LIST_TRAVERSE(&queries, query, list) {
256                 if (!strcmp(query->acf->name, cmd)) {
257                         break;
258                 }
259         }
260
261         if (!query) {
262                 ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
263                 AST_LIST_UNLOCK(&queries);
264                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
265                 return -1;
266         }
267
268         AST_STANDARD_APP_ARGS(args, s);
269         for (x = 0; x < args.argc; x++) {
270                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
271                 pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
272         }
273
274         pbx_substitute_variables_helper(chan, query->sql_read, sql, sizeof(sql) - 1);
275
276         /* Restore prior values */
277         for (x = 0; x < args.argc; x++) {
278                 snprintf(varname, sizeof(varname), "ARG%d", x + 1);
279                 pbx_builtin_setvar_helper(chan, varname, NULL);
280         }
281
282         /* Save these flags, so we can release the lock */
283         escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
284         if (ast_test_flag(query, OPT_MULTIROW)) {
285                 resultset = ast_calloc(1, sizeof(*resultset));
286                 AST_LIST_HEAD_INIT(resultset);
287                 if (query->rowlimit)
288                         rowlimit = query->rowlimit;
289                 else
290                         rowlimit = INT_MAX;
291         }
292         AST_LIST_UNLOCK(&queries);
293
294         for (dsn = 0; dsn < 5; dsn++) {
295                 if (!ast_strlen_zero(query->writehandle[dsn])) {
296                         obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
297                         if (obj)
298                                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql);
299                 }
300                 if (stmt)
301                         break;
302         }
303
304         if (!stmt) {
305                 ast_log(LOG_ERROR, "Unable to execute query [%s]\n", sql);
306                 if (obj)
307                         ast_odbc_release_obj(obj);
308                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
309                 return -1;
310         }
311
312         res = SQLNumResultCols(stmt, &colcount);
313         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
314                 ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
315                 SQLCloseCursor(stmt);
316                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
317                 ast_odbc_release_obj(obj);
318                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
319                 return -1;
320         }
321
322         res = SQLFetch(stmt);
323         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
324                 int res1 = -1;
325                 if (res == SQL_NO_DATA) {
326                         ast_verb(4, "Found no rows [%s]\n", sql);
327                         res1 = 0;
328                         ast_copy_string(rowcount, "0", sizeof(rowcount));
329                 } else {
330                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
331                 }
332                 SQLCloseCursor(stmt);
333                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
334                 ast_odbc_release_obj(obj);
335                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
336                 return res1;
337         }
338
339         for (y = 0; y < rowlimit; y++) {
340                 *buf = '\0';
341                 for (x = 0; x < colcount; x++) {
342                         int i;
343                         char coldata[256];
344
345                         if (y == 0) {
346                                 char colname[256];
347                                 int namelen;
348
349                                 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, NULL, NULL, NULL);
350                                 if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
351                                         snprintf(colname, sizeof(colname), "field%d", x);
352                                 }
353
354                                 if (!ast_strlen_zero(colnames))
355                                         strncat(colnames, ",", sizeof(colnames) - 1);
356                                 namelen = strlen(colnames);
357
358                                 /* Copy data, encoding '\' and ',' for the argument parser */
359                                 for (i = 0; i < sizeof(colname); i++) {
360                                         if (escapecommas && (colname[i] == '\\' || colname[i] == ',')) {
361                                                 colnames[namelen++] = '\\';
362                                         }
363                                         colnames[namelen++] = colname[i];
364
365                                         if (namelen >= sizeof(colnames) - 2) {
366                                                 colnames[namelen >= sizeof(colnames) ? sizeof(colnames) - 1 : namelen] = '\0';
367                                                 break;
368                                         }
369
370                                         if (colname[i] == '\0')
371                                                 break;
372                                 }
373
374                                 if (resultset) {
375                                         void *tmp = ast_realloc(resultset, sizeof(*resultset) + strlen(colnames) + 1);
376                                         if (!tmp) {
377                                                 ast_log(LOG_ERROR, "No space for a new resultset?\n");
378                                                 ast_free(resultset);
379                                                 SQLCloseCursor(stmt);
380                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
381                                                 ast_odbc_release_obj(obj);
382                                                 pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
383                                                 return -1;
384                                         }
385                                         resultset = tmp;
386                                         strcpy((char *)resultset + sizeof(*resultset), colnames);
387                                 }
388                         }
389
390                         buflen = strlen(buf);
391                         res = SQLGetData(stmt, x + 1, SQL_CHAR, coldata, sizeof(coldata), &indicator);
392                         if (indicator == SQL_NULL_DATA) {
393                                 coldata[0] = '\0';
394                                 res = SQL_SUCCESS;
395                         }
396
397                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
398                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
399                                 y = -1;
400                                 goto end_acf_read;
401                         }
402
403                         /* Copy data, encoding '\' and ',' for the argument parser */
404                         for (i = 0; i < sizeof(coldata); i++) {
405                                 if (escapecommas && (coldata[i] == '\\' || coldata[i] == ',')) {
406                                         buf[buflen++] = '\\';
407                                 }
408                                 buf[buflen++] = coldata[i];
409
410                                 if (buflen >= len - 2)
411                                         break;
412
413                                 if (coldata[i] == '\0')
414                                         break;
415                         }
416
417                         buf[buflen - 1] = ',';
418                         buf[buflen] = '\0';
419                 }
420                 /* Trim trailing comma */
421                 buf[buflen - 1] = '\0';
422
423                 if (resultset) {
424                         row = ast_calloc(1, sizeof(*row) + buflen);
425                         if (!row) {
426                                 ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
427                                 goto end_acf_read;
428                         }
429                         strcpy((char *)row + sizeof(*row), buf);
430                         AST_LIST_INSERT_TAIL(resultset, row, list);
431
432                         /* Get next row */
433                         res = SQLFetch(stmt);
434                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
435                                 if (res != SQL_NO_DATA)
436                                         ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, sql);
437                                 y++;
438                                 break;
439                         }
440                 }
441         }
442
443 end_acf_read:
444         snprintf(rowcount, sizeof(rowcount), "%d", y);
445         pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
446         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", colnames);
447         if (resultset) {
448                 int uid;
449                 struct ast_datastore *odbc_store;
450                 uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
451                 snprintf(buf, len, "%d", uid);
452                 odbc_store = ast_channel_datastore_alloc(&odbc_info, buf);
453                 if (!odbc_store) {
454                         ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel.  Results fail.\n");
455                         odbc_datastore_free(resultset);
456                         SQLCloseCursor(stmt);
457                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
458                         ast_odbc_release_obj(obj);
459                         return -1;
460                 }
461                 odbc_store->data = resultset;
462                 ast_channel_datastore_add(chan, odbc_store);
463         }
464         SQLCloseCursor(stmt);
465         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
466         ast_odbc_release_obj(obj);
467         return 0;
468 }
469
470 static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
471 {
472         char *out = buf;
473
474         for (; *data && out - buf < len; data++) {
475                 if (*data == '\'') {
476                         *out = '\'';
477                         out++;
478                 }
479                 *out++ = *data;
480         }
481         *out = '\0';
482
483         return 0;
484 }
485
486 static struct ast_custom_function escape_function = {
487         .name = "SQL_ESC",
488         .synopsis = "Escapes single ticks for use in SQL statements",
489         .syntax = "SQL_ESC(<string>)",
490         .desc =
491 "Used in SQL templates to escape data which may contain single ticks (') which\n"
492 "are otherwise used to delimit data.  For example:\n"
493 "SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'\n",
494         .read = acf_escape,
495         .write = NULL,
496 };
497
498 static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
499 {
500         struct ast_datastore *store;
501         struct odbc_datastore *resultset;
502         struct odbc_datastore_row *row;
503         store = ast_channel_datastore_find(chan, &odbc_info, data);
504         if (!store) {
505                 return -1;
506         }
507         resultset = store->data;
508         AST_LIST_LOCK(resultset);
509         row = AST_LIST_REMOVE_HEAD(resultset, list);
510         AST_LIST_UNLOCK(resultset);
511         if (!row) {
512                 /* Cleanup datastore */
513                 ast_channel_datastore_remove(chan, store);
514                 ast_channel_datastore_free(store);
515                 return -1;
516         }
517         pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
518         ast_copy_string(buf, row->data, len);
519         ast_free(row);
520         return 0;
521 }
522
523 static struct ast_custom_function fetch_function = {
524         .name = "ODBC_FETCH",
525         .synopsis = "Fetch a row from a multirow query",
526         .syntax = "ODBC_FETCH(<result-id>)",
527         .desc =
528 "For queries which are marked as mode=multirow, the original query returns a\n"
529 "result-id from which results may be fetched.  This function implements the\n"
530 "actual fetch of the results.\n",
531         .read = acf_fetch,
532         .write = NULL,
533 };
534
535 static char *app_odbcfinish = "ODBCFinish";
536 static char *syn_odbcfinish = "Clear the resultset of a successful multirow query";
537 static char *desc_odbcfinish =
538 "ODBCFinish(<result-id>)\n"
539 "  Clears any remaining rows of the specified resultset\n";
540
541
542 static int exec_odbcfinish(struct ast_channel *chan, void *data)
543 {
544         struct ast_datastore *store = ast_channel_datastore_find(chan, &odbc_info, data);
545         if (!store) /* Already freed; no big deal. */
546                 return 0;
547         ast_channel_datastore_remove(chan, store);
548         ast_channel_datastore_free(store);
549         return 0;
550 }
551
552 static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
553 {
554         const char *tmp;
555         int i;
556
557         if (!cfg || !catg) {
558                 return EINVAL;
559         }
560
561         *query = ast_calloc(1, sizeof(struct acf_odbc_query));
562         if (! (*query))
563                 return ENOMEM;
564
565         if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
566                 char *tmp2 = ast_strdupa(tmp);
567                 AST_DECLARE_APP_ARGS(write,
568                         AST_APP_ARG(dsn)[5];
569                 );
570                 AST_NONSTANDARD_APP_ARGS(write, tmp2, ',');
571                 for (i = 0; i < 5; i++) {
572                         if (!ast_strlen_zero(write.dsn[i]))
573                                 ast_copy_string((*query)->writehandle[i], write.dsn[i], sizeof((*query)->writehandle[i]));
574                 }
575         }
576
577         if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
578                 char *tmp2 = ast_strdupa(tmp);
579                 AST_DECLARE_APP_ARGS(read,
580                         AST_APP_ARG(dsn)[5];
581                 );
582                 AST_NONSTANDARD_APP_ARGS(read, tmp2, ',');
583                 for (i = 0; i < 5; i++) {
584                         if (!ast_strlen_zero(read.dsn[i]))
585                                 ast_copy_string((*query)->readhandle[i], read.dsn[i], sizeof((*query)->readhandle[i]));
586                 }
587         } else {
588                 /* If no separate readhandle, then use the writehandle for reading */
589                 for (i = 0; i < 5; i++) {
590                         if (!ast_strlen_zero((*query)->writehandle[i]))
591                                 ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
592                 }
593         }
594
595         if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")))
596                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
597         else if ((tmp = ast_variable_retrieve(cfg, catg, "read"))) {
598                 ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s.  Please use 'readsql' instead.\n", catg);
599                 ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
600         }
601
602         if (!ast_strlen_zero((*query)->sql_read) && ast_strlen_zero((*query)->readhandle[0])) {
603                 ast_free(*query);
604                 *query = NULL;
605                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
606                 return EINVAL;
607         }
608
609         if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")))
610                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
611         else if ((tmp = ast_variable_retrieve(cfg, catg, "write"))) {
612                 ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s.  Please use 'writesql' instead.\n", catg);
613                 ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
614         }
615
616         if (!ast_strlen_zero((*query)->sql_write) && ast_strlen_zero((*query)->writehandle[0])) {
617                 ast_free(*query);
618                 *query = NULL;
619                 ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
620                 return EINVAL;
621         }
622
623         /* Allow escaping of embedded commas in fields to be turned off */
624         ast_set_flag((*query), OPT_ESCAPECOMMAS);
625         if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
626                 if (ast_false(tmp))
627                         ast_clear_flag((*query), OPT_ESCAPECOMMAS);
628         }
629
630         if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
631                 if (strcasecmp(tmp, "multirow") == 0)
632                         ast_set_flag((*query), OPT_MULTIROW);
633                 if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
634                         sscanf(tmp, "%d", &((*query)->rowlimit));
635         }
636
637         (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
638         if (! (*query)->acf) {
639                 ast_free(*query);
640                 *query = NULL;
641                 return ENOMEM;
642         }
643
644         if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
645                 asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg);
646         } else {
647                 asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg);
648         }
649
650         if (!((*query)->acf->name)) {
651                 ast_free((*query)->acf);
652                 ast_free(*query);
653                 *query = NULL;
654                 return ENOMEM;
655         }
656
657         asprintf((char **)&((*query)->acf->syntax), "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
658
659         if (!((*query)->acf->syntax)) {
660                 ast_free((char *)(*query)->acf->name);
661                 ast_free((*query)->acf);
662                 ast_free(*query);
663                 *query = NULL;
664                 return ENOMEM;
665         }
666
667         (*query)->acf->synopsis = "Runs the referenced query with the specified arguments";
668         if (!ast_strlen_zero((*query)->sql_read) && !ast_strlen_zero((*query)->sql_write)) {
669                 asprintf((char **)&((*query)->acf->desc),
670                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
671                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
672                                         "${ARG2}, ... ${ARGn}.  When setting the function, the values are provided\n"
673                                         "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
674                                         "\nRead:\n%s\n\nWrite:\n%s\n",
675                                         (*query)->sql_read,
676                                         (*query)->sql_write);
677         } else if (!ast_strlen_zero((*query)->sql_read)) {
678                 asprintf((char **)&((*query)->acf->desc),
679                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
680                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
681                                         "${ARG2}, ... ${ARGn}.  This function may only be read, not set.\n\nSQL:\n%s\n",
682                                         (*query)->sql_read);
683         } else if (!ast_strlen_zero((*query)->sql_write)) {
684                 asprintf((char **)&((*query)->acf->desc),
685                                         "Runs the following query, as defined in func_odbc.conf, performing\n"
686                                         "substitution of the arguments into the query as specified by ${ARG1},\n"
687                                         "${ARG2}, ... ${ARGn}.  The values are provided either in whole as\n"
688                                         "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
689                                         "This function may only be set.\nSQL:\n%s\n",
690                                         (*query)->sql_write);
691         } else {
692                 ast_free((char *)(*query)->acf->syntax);
693                 ast_free((char *)(*query)->acf->name);
694                 ast_free((*query)->acf);
695                 ast_free(*query);
696                 ast_log(LOG_WARNING, "Section %s was found, but there was no SQL to execute.  Ignoring.\n", catg);
697                 return EINVAL;
698         }
699
700         if (! ((*query)->acf->desc)) {
701                 ast_free((char *)(*query)->acf->syntax);
702                 ast_free((char *)(*query)->acf->name);
703                 ast_free((*query)->acf);
704                 ast_free(*query);
705                 *query = NULL;
706                 return ENOMEM;
707         }
708
709         if (ast_strlen_zero((*query)->sql_read)) {
710                 (*query)->acf->read = NULL;
711         } else {
712                 (*query)->acf->read = acf_odbc_read;
713         }
714
715         if (ast_strlen_zero((*query)->sql_write)) {
716                 (*query)->acf->write = NULL;
717         } else {
718                 (*query)->acf->write = acf_odbc_write;
719         }
720
721         return 0;
722 }
723
724 static int free_acf_query(struct acf_odbc_query *query)
725 {
726         if (query) {
727                 if (query->acf) {
728                         if (query->acf->name)
729                                 ast_free((char *)query->acf->name);
730                         if (query->acf->syntax)
731                                 ast_free((char *)query->acf->syntax);
732                         if (query->acf->desc)
733                                 ast_free((char *)query->acf->desc);
734                         ast_free(query->acf);
735                 }
736                 ast_free(query);
737         }
738         return 0;
739 }
740
741 static int load_module(void)
742 {
743         int res = 0;
744         struct ast_config *cfg;
745         char *catg;
746         struct ast_flags config_flags = { 0 };
747
748         res |= ast_custom_function_register(&fetch_function);
749         res |= ast_register_application(app_odbcfinish, exec_odbcfinish, syn_odbcfinish, desc_odbcfinish);
750         AST_LIST_LOCK(&queries);
751
752         cfg = ast_config_load(config, config_flags);
753         if (!cfg) {
754                 ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
755                 AST_LIST_UNLOCK(&queries);
756                 return AST_MODULE_LOAD_DECLINE;
757         }
758
759         for (catg = ast_category_browse(cfg, NULL);
760              catg;
761              catg = ast_category_browse(cfg, catg)) {
762                 struct acf_odbc_query *query = NULL;
763                 int err;
764
765                 if ((err = init_acf_query(cfg, catg, &query))) {
766                         if (err == ENOMEM)
767                                 ast_log(LOG_ERROR, "Out of memory\n");
768                         else if (err == EINVAL)
769                                 ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
770                         else
771                                 ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
772                 } else {
773                         AST_LIST_INSERT_HEAD(&queries, query, list);
774                         ast_custom_function_register(query->acf);
775                 }
776         }
777
778         ast_config_destroy(cfg);
779         res |= ast_custom_function_register(&escape_function);
780
781         AST_LIST_UNLOCK(&queries);
782         return res;
783 }
784
785 static int unload_module(void)
786 {
787         struct acf_odbc_query *query;
788         int res = 0;
789
790         AST_LIST_LOCK(&queries);
791         while (!AST_LIST_EMPTY(&queries)) {
792                 query = AST_LIST_REMOVE_HEAD(&queries, list);
793                 ast_custom_function_unregister(query->acf);
794                 free_acf_query(query);
795         }
796
797         res |= ast_custom_function_unregister(&escape_function);
798         res |= ast_custom_function_unregister(&fetch_function);
799         res |= ast_unregister_application(app_odbcfinish);
800
801         /* Allow any threads waiting for this lock to pass (avoids a race) */
802         AST_LIST_UNLOCK(&queries);
803         usleep(1);
804         AST_LIST_LOCK(&queries);
805
806         AST_LIST_UNLOCK(&queries);
807         return 0;
808 }
809
810 static int reload(void)
811 {
812         int res = 0;
813         struct ast_config *cfg;
814         struct acf_odbc_query *oldquery;
815         char *catg;
816         struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
817
818         cfg = ast_config_load(config, config_flags);
819         if (cfg == CONFIG_STATUS_FILEUNCHANGED)
820                 return 0;
821
822         AST_LIST_LOCK(&queries);
823
824         while (!AST_LIST_EMPTY(&queries)) {
825                 oldquery = AST_LIST_REMOVE_HEAD(&queries, list);
826                 ast_custom_function_unregister(oldquery->acf);
827                 free_acf_query(oldquery);
828         }
829
830         if (!cfg) {
831                 ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
832                 goto reload_out;
833         }
834
835         for (catg = ast_category_browse(cfg, NULL);
836              catg;
837              catg = ast_category_browse(cfg, catg)) {
838                 struct acf_odbc_query *query = NULL;
839
840                 if (init_acf_query(cfg, catg, &query)) {
841                         ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
842                 } else {
843                         AST_LIST_INSERT_HEAD(&queries, query, list);
844                         ast_custom_function_register(query->acf);
845                 }
846         }
847
848         ast_config_destroy(cfg);
849 reload_out:
850         AST_LIST_UNLOCK(&queries);
851         return res;
852 }
853
854 /* XXX need to revise usecount - set if query_lock is set */
855
856 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
857                 .load = load_module,
858                 .unload = unload_module,
859                 .reload = reload,
860                );
861