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