cel_pgsql.c: Fix buffer overflow calling libpq
[asterisk/asterisk.git] / cel / cel_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008
5  *
6  * Steve Murphy - adapted to CEL, from:
7  * Matthew D. Hardeman <mhardemn@papersoft.com>
8  * Adapted from the MySQL CDR logger originally by James Sharp
9  *
10  * Modified April, 2007; Dec, 2008
11  * Steve Murphy <murf@digium.com>
12
13  * Modified September 2003
14  * Matthew D. Hardeman <mhardemn@papersoft.com>
15  *
16  * See http://www.asterisk.org for more information about
17  * the Asterisk project. Please do not directly contact
18  * any of the maintainers of this project for assistance;
19  * the project provides a web site, mailing lists and IRC
20  * channels for your use.
21  *
22  * This program is free software, distributed under the terms of
23  * the GNU General Public License Version 2. See the LICENSE file
24  * at the top of the source tree.
25  */
26
27 /*! \file
28  *
29  * \brief PostgreSQL CEL logger
30  *
31  * \author Steve Murphy <murf@digium.com>
32  * PostgreSQL http://www.postgresql.org/
33  *
34  * See also
35  * \arg \ref Config_cel
36  * PostgreSQL http://www.postgresql.org/
37  * \ingroup cel_drivers
38  */
39
40 /*** MODULEINFO
41         <depend>pgsql</depend>
42         <support_level>extended</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 #include <libpq-fe.h>
48
49 #include "asterisk/config.h"
50 #include "asterisk/options.h"
51 #include "asterisk/channel.h"
52 #include "asterisk/cel.h"
53 #include "asterisk/module.h"
54 #include "asterisk/logger.h"
55 #include "asterisk.h"
56
57 #define DATE_FORMAT "%Y-%m-%d %T.%6q"
58
59 #define PGSQL_BACKEND_NAME "CEL PGSQL backend"
60
61 #define PGSQL_MIN_VERSION_SCHEMA 70300
62
63 static char *config = "cel_pgsql.conf";
64
65 static char *pghostname;
66 static char *pgdbname;
67 static char *pgdbuser;
68 static char *pgpassword;
69 static char *pgappname;
70 static char *pgdbport;
71 static char *table;
72 static char *schema;
73
74 static int connected = 0;
75 /* Optimization to reduce number of memory allocations */
76 static int maxsize = 512, maxsize2 = 512;
77 static int usegmtime = 0;
78
79 /*! \brief show_user_def is off by default */
80 #define CEL_SHOW_USERDEF_DEFAULT        0
81
82 /*! TRUE if we should set the eventtype field to USER_DEFINED on user events. */
83 static unsigned char cel_show_user_def;
84
85 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
86
87 static PGconn   *conn = NULL;
88 static PGresult *result = NULL;
89
90 struct columns {
91         char *name;
92         char *type;
93         int len;
94         unsigned int notnull:1;
95         unsigned int hasdefault:1;
96         AST_RWLIST_ENTRY(columns) list;
97 };
98
99 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
100
101 #define LENGTHEN_BUF(size, var_sql) \
102         do { \
103                 /* Lengthen buffer, if necessary */ \
104                 if (ast_str_strlen(var_sql) + size + 1 > ast_str_size(var_sql)) { \
105                         if (ast_str_make_space(&var_sql, ((ast_str_size(var_sql) + size + 3) / 512 + 1) * 512) != 0) { \
106                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", pghostname, table); \
107                                 ast_free(sql); \
108                                 ast_free(sql2); \
109                                 AST_RWLIST_UNLOCK(&psql_columns); \
110                                 return; \
111                         } \
112                 } \
113         } while (0)
114
115 #define LENGTHEN_BUF1(size) \
116         LENGTHEN_BUF(size, sql);
117 #define LENGTHEN_BUF2(size) \
118         LENGTHEN_BUF(size, sql2);
119
120 static void pgsql_reconnect(void)
121 {
122         struct ast_str *conn_info = ast_str_create(128);
123         if (!conn_info) {
124                 ast_log(LOG_ERROR, "Failed to allocate memory for connection string.\n");
125                 return;
126         }
127
128         if (conn) {
129                 PQfinish(conn);
130                 conn = NULL;
131         }
132
133         ast_str_set(&conn_info, 0, "host=%s port=%s dbname=%s user=%s",
134                 pghostname, pgdbport, pgdbname, pgdbuser);
135
136         if (!ast_strlen_zero(pgappname)) {
137                 ast_str_append(&conn_info, 0, " application_name=%s", pgappname);
138         }
139
140         if (!ast_strlen_zero(pgpassword)) {
141                 ast_str_append(&conn_info, 0, " password=%s", pgpassword);
142         }
143
144         conn = PQconnectdb(ast_str_buffer(conn_info));
145         ast_free(conn_info);
146 }
147
148
149 static void pgsql_log(struct ast_event *event)
150 {
151         struct ast_tm tm;
152         char timestr[128];
153         char *pgerror;
154         struct ast_cel_event_record record = {
155                 .version = AST_CEL_EVENT_RECORD_VERSION,
156         };
157
158         if (ast_cel_fill_record(event, &record)) {
159                 return;
160         }
161
162         ast_mutex_lock(&pgsql_lock);
163
164         ast_localtime(&record.event_time, &tm, usegmtime ? "GMT" : NULL);
165         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
166
167         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
168                 pgsql_reconnect();
169                 if (PQstatus(conn) != CONNECTION_BAD) {
170                         connected = 1;
171                 } else {
172                         pgerror = PQerrorMessage(conn);
173                         ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
174                         ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
175                         PQfinish(conn);
176                         conn = NULL;
177                 }
178         }
179         if (connected) {
180                 struct columns *cur;
181                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
182                 char buf[257];
183                 char *escapebuf = NULL;
184                 const char *value;
185                 int first = 1;
186                 size_t bufsize = 513;
187
188                 escapebuf = ast_malloc(bufsize);
189                 if (!escapebuf || !sql || !sql2) {
190                         goto ast_log_cleanup;
191                 }
192
193                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
194                 ast_str_set(&sql2, 0, " VALUES (");
195
196 #define SEP (first ? "" : ",")
197
198                 AST_RWLIST_RDLOCK(&psql_columns);
199                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
200                         LENGTHEN_BUF1(strlen(cur->name) + 2);
201                         ast_str_append(&sql, 0, "%s\"%s\"", SEP, cur->name);
202
203                         if (strcmp(cur->name, "eventtime") == 0) {
204                                 if (strncmp(cur->type, "int", 3) == 0) {
205                                         LENGTHEN_BUF2(13);
206                                         ast_str_append(&sql2, 0, "%s%ld", SEP, (long) record.event_time.tv_sec);
207                                 } else if (strncmp(cur->type, "float", 5) == 0) {
208                                         LENGTHEN_BUF2(31);
209                                         ast_str_append(&sql2, 0, "%s%f",
210                                                 SEP,
211                                                 (double) record.event_time.tv_sec +
212                                                 (double) record.event_time.tv_usec / 1000000.0);
213                                 } else {
214                                         /* char, hopefully */
215                                         LENGTHEN_BUF2(31);
216                                         ast_localtime(&record.event_time, &tm, usegmtime ? "GMT" : NULL);
217                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
218                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, buf);
219                                 }
220                         } else if (strcmp(cur->name, "eventtype") == 0) {
221                                 if (cur->type[0] == 'i') {
222                                         /* Get integer, no need to escape anything */
223                                         LENGTHEN_BUF2(5);
224                                         ast_str_append(&sql2, 0, "%s%d", SEP, (int) record.event_type);
225                                 } else if (strncmp(cur->type, "float", 5) == 0) {
226                                         LENGTHEN_BUF2(31);
227                                         ast_str_append(&sql2, 0, "%s%f", SEP, (double) record.event_type);
228                                 } else {
229                                         /* Char field, probably */
230                                         const char *event_name;
231
232                                         event_name = (!cel_show_user_def
233                                                 && record.event_type == AST_CEL_USER_DEFINED)
234                                                 ? record.user_defined_name : record.event_name;
235                                         LENGTHEN_BUF2(strlen(event_name) + 1);
236                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, event_name);
237                                 }
238                         } else if (strcmp(cur->name, "amaflags") == 0) {
239                                 if (strncmp(cur->type, "int", 3) == 0) {
240                                         /* Integer, no need to escape anything */
241                                         LENGTHEN_BUF2(13);
242                                         ast_str_append(&sql2, 0, "%s%u", SEP, record.amaflag);
243                                 } else {
244                                         /* Although this is a char field, there are no special characters in the values for these fields */
245                                         LENGTHEN_BUF2(31);
246                                         ast_str_append(&sql2, 0, "%s'%u'", SEP, record.amaflag);
247                                 }
248                         } else {
249                                 /* Arbitrary field, could be anything */
250                                 if (strcmp(cur->name, "userdeftype") == 0) {
251                                         value = record.user_defined_name;
252                                 } else if (strcmp(cur->name, "cid_name") == 0) {
253                                         value = record.caller_id_name;
254                                 } else if (strcmp(cur->name, "cid_num") == 0) {
255                                         value = record.caller_id_num;
256                                 } else if (strcmp(cur->name, "cid_ani") == 0) {
257                                         value = record.caller_id_ani;
258                                 } else if (strcmp(cur->name, "cid_rdnis") == 0) {
259                                         value = record.caller_id_rdnis;
260                                 } else if (strcmp(cur->name, "cid_dnid") == 0) {
261                                         value = record.caller_id_dnid;
262                                 } else if (strcmp(cur->name, "exten") == 0) {
263                                         value = record.extension;
264                                 } else if (strcmp(cur->name, "context") == 0) {
265                                         value = record.context;
266                                 } else if (strcmp(cur->name, "channame") == 0) {
267                                         value = record.channel_name;
268                                 } else if (strcmp(cur->name, "appname") == 0) {
269                                         value = record.application_name;
270                                 } else if (strcmp(cur->name, "appdata") == 0) {
271                                         value = record.application_data;
272                                 } else if (strcmp(cur->name, "accountcode") == 0) {
273                                         value = record.account_code;
274                                 } else if (strcmp(cur->name, "peeraccount") == 0) {
275                                         value = record.peer_account;
276                                 } else if (strcmp(cur->name, "uniqueid") == 0) {
277                                         value = record.unique_id;
278                                 } else if (strcmp(cur->name, "linkedid") == 0) {
279                                         value = record.linked_id;
280                                 } else if (strcmp(cur->name, "userfield") == 0) {
281                                         value = record.user_field;
282                                 } else if (strcmp(cur->name, "peer") == 0) {
283                                         value = record.peer;
284                                 } else if (strcmp(cur->name, "extra") == 0) {
285                                         value = record.extra;
286                                 } else {
287                                         value = NULL;
288                                 }
289
290                                 if (value == NULL) {
291                                         ast_str_append(&sql2, 0, "%sDEFAULT", SEP);
292                                 } else if (strncmp(cur->type, "int", 3) == 0) {
293                                         long long whatever;
294                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
295                                                 LENGTHEN_BUF2(26);
296                                                 ast_str_append(&sql2, 0, "%s%lld", SEP, whatever);
297                                         } else {
298                                                 LENGTHEN_BUF2(2);
299                                                 ast_str_append(&sql2, 0, "%s0", SEP);
300                                         }
301                                 } else if (strncmp(cur->type, "float", 5) == 0) {
302                                         long double whatever;
303                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
304                                                 LENGTHEN_BUF2(51);
305                                                 ast_str_append(&sql2, 0, "%s%30Lf", SEP, whatever);
306                                         } else {
307                                                 LENGTHEN_BUF2(2);
308                                                 ast_str_append(&sql2, 0, "%s0", SEP);
309                                         }
310                                         /* XXX Might want to handle dates, times, and other misc fields here XXX */
311                                 } else {
312                                         if (value) {
313                                                 size_t required_size = strlen(value) * 2 + 1;
314
315                                                 /* If our argument size exceeds our buffer, grow it,
316                                                  * as PQescapeStringConn() expects the buffer to be
317                                                  * adequitely sized and does *NOT* do size checking.
318                                                  */
319                                                 if (required_size > bufsize) {
320                                                         char *tmpbuf = ast_realloc(escapebuf, required_size);
321
322                                                         if (!tmpbuf) {
323                                                                 goto ast_log_cleanup;
324                                                         }
325
326                                                         escapebuf = tmpbuf;
327                                                         bufsize = required_size;
328                                                 }
329                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
330                                         } else {
331                                                 escapebuf[0] = '\0';
332                                         }
333                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
334                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, escapebuf);
335                                 }
336                         }
337                         first = 0;
338                 }
339                 AST_RWLIST_UNLOCK(&psql_columns);
340                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
341                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
342
343                 ast_debug(3, "Inserting a CEL record: [%s].\n", ast_str_buffer(sql));
344                 /* Test to be sure we're still connected... */
345                 /* If we're connected, and connection is working, good. */
346                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
347                 if (PQstatus(conn) == CONNECTION_OK) {
348                         connected = 1;
349                 } else {
350                         ast_log(LOG_WARNING, "Connection was lost... attempting to reconnect.\n");
351                         PQreset(conn);
352                         if (PQstatus(conn) == CONNECTION_OK) {
353                                 ast_log(LOG_NOTICE, "Connection reestablished.\n");
354                                 connected = 1;
355                         } else {
356                                 pgerror = PQerrorMessage(conn);
357                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
358                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
359                                 PQfinish(conn);
360                                 conn = NULL;
361                                 connected = 0;
362                                 goto ast_log_cleanup;
363                         }
364                 }
365                 result = PQexec(conn, ast_str_buffer(sql));
366                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
367                         pgerror = PQresultErrorMessage(result);
368                         ast_log(LOG_WARNING, "Failed to insert call detail record into database!\n");
369                         ast_log(LOG_WARNING, "Reason: %s\n", pgerror);
370                         ast_log(LOG_WARNING, "Connection may have been lost... attempting to reconnect.\n");
371                         PQreset(conn);
372                         if (PQstatus(conn) == CONNECTION_OK) {
373                                 ast_log(LOG_NOTICE, "Connection reestablished.\n");
374                                 connected = 1;
375                                 PQclear(result);
376                                 result = PQexec(conn, ast_str_buffer(sql));
377                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
378                                         pgerror = PQresultErrorMessage(result);
379                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
380                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
381                                 }
382                         }
383                         PQclear(result);
384                         goto ast_log_cleanup;
385                 }
386                 PQclear(result);
387
388                 /* Next time, just allocate buffers that are that big to start with. */
389                 if (ast_str_strlen(sql) > maxsize) {
390                         maxsize = ast_str_strlen(sql);
391                 }
392                 if (ast_str_strlen(sql2) > maxsize2) {
393                         maxsize2 = ast_str_strlen(sql2);
394                 }
395
396 ast_log_cleanup:
397                 ast_free(sql);
398                 ast_free(sql2);
399                 ast_free(escapebuf);
400         }
401
402         ast_mutex_unlock(&pgsql_lock);
403 }
404
405 static int my_unload_module(void)
406 {
407         struct columns *current;
408
409         ast_cel_backend_unregister(PGSQL_BACKEND_NAME);
410         AST_RWLIST_WRLOCK(&psql_columns);
411         if (conn) {
412                 PQfinish(conn);
413                 conn = NULL;
414         }
415         if (pghostname) {
416                 ast_free(pghostname);
417                 pghostname = NULL;
418         }
419         if (pgdbname) {
420                 ast_free(pgdbname);
421                 pgdbname = NULL;
422         }
423         if (pgdbuser) {
424                 ast_free(pgdbuser);
425                 pgdbuser = NULL;
426         }
427         if (pgpassword) {
428                 ast_free(pgpassword);
429                 pgpassword = NULL;
430         }
431         if (pgappname) {
432                 ast_free(pgappname);
433                 pgappname = NULL;
434         }
435         if (pgdbport) {
436                 ast_free(pgdbport);
437                 pgdbport = NULL;
438         }
439         if (table) {
440                 ast_free(table);
441                 table = NULL;
442         }
443         if (schema) {
444                 ast_free(schema);
445                 schema = NULL;
446         }
447         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
448                 ast_free(current);
449         }
450         AST_RWLIST_UNLOCK(&psql_columns);
451         return 0;
452 }
453
454 static int unload_module(void)
455 {
456         return my_unload_module();
457 }
458
459 static int process_my_load_module(struct ast_config *cfg)
460 {
461         struct ast_variable *var;
462         char *pgerror;
463         const char *tmp;
464         PGresult *result;
465         struct columns *cur;
466
467         if (!(var = ast_variable_browse(cfg, "global"))) {
468                 ast_log(LOG_WARNING,"CEL pgsql config file missing global section.\n");
469                 return AST_MODULE_LOAD_DECLINE;
470         }
471         if (!(tmp = ast_variable_retrieve(cfg,"global","hostname"))) {
472                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
473                 tmp = "";       /* connect via UNIX-socket by default */
474         }
475         if (pghostname)
476                 ast_free(pghostname);
477         if (!(pghostname = ast_strdup(tmp))) {
478                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying host info\n");
479                 return AST_MODULE_LOAD_DECLINE;
480         }
481         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
482                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
483                 tmp = "asteriskceldb";
484         }
485         if (pgdbname)
486                 ast_free(pgdbname);
487         if (!(pgdbname = ast_strdup(tmp))) {
488                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying dbname info\n");
489                 return AST_MODULE_LOAD_DECLINE;
490         }
491         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
492                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
493                 tmp = "asterisk";
494         }
495         if (pgdbuser)
496                 ast_free(pgdbuser);
497         if (!(pgdbuser = ast_strdup(tmp))) {
498                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying user info\n");
499                 return AST_MODULE_LOAD_DECLINE;
500         }
501         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
502                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
503                 tmp = "";
504         }
505         if (pgpassword)
506                 ast_free(pgpassword);
507         if (!(pgpassword = ast_strdup(tmp))) {
508                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying password info\n");
509                 return AST_MODULE_LOAD_DECLINE;
510         }
511         if (!(tmp = ast_variable_retrieve(cfg, "global", "appname"))) {
512                 tmp = "";
513         }
514         if (pgappname) {
515                 ast_free(pgappname);
516         }
517         if (!(pgappname = ast_strdup(tmp))) {
518                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying appname info\n");
519                 return AST_MODULE_LOAD_DECLINE;
520         }
521
522         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
523                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
524                 tmp = "5432";
525         }
526         if (pgdbport)
527                 ast_free(pgdbport);
528         if (!(pgdbport = ast_strdup(tmp))) {
529                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying port info\n");
530                 return AST_MODULE_LOAD_DECLINE;
531         }
532         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
533                 ast_log(LOG_WARNING,"CEL table not specified.  Assuming cel\n");
534                 tmp = "cel";
535         }
536         if (table)
537                 ast_free(table);
538         if (!(table = ast_strdup(tmp))) {
539                 return AST_MODULE_LOAD_DECLINE;
540         }
541         cel_show_user_def = CEL_SHOW_USERDEF_DEFAULT;
542         if ((tmp = ast_variable_retrieve(cfg, "global", "show_user_defined"))) {
543                 cel_show_user_def = ast_true(tmp) ? 1 : 0;
544         }
545         if ((tmp = ast_variable_retrieve(cfg, "global", "usegmtime"))) {
546                 usegmtime = ast_true(tmp);
547         } else {
548                 usegmtime = 0;
549         }
550         if (!(tmp = ast_variable_retrieve(cfg, "global", "schema"))) {
551                 tmp = "";
552         }
553         if (schema) {
554                 ast_free(schema);
555         }
556         if (!(schema = ast_strdup(tmp))) {
557                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying schema info\n");
558                 return AST_MODULE_LOAD_DECLINE;
559         }
560         if (option_debug) {
561                 if (ast_strlen_zero(pghostname)) {
562                         ast_debug(3, "cel_pgsql: using default unix socket\n");
563                 } else {
564                         ast_debug(3, "cel_pgsql: got hostname of %s\n", pghostname);
565                 }
566                 ast_debug(3, "cel_pgsql: got port of %s\n", pgdbport);
567                 ast_debug(3, "cel_pgsql: got user of %s\n", pgdbuser);
568                 ast_debug(3, "cel_pgsql: got dbname of %s\n", pgdbname);
569                 ast_debug(3, "cel_pgsql: got password of %s\n", pgpassword);
570                 ast_debug(3, "cel_pgsql: got sql table name of %s\n", table);
571                 ast_debug(3, "cel_pgsql: got show_user_defined of %s\n",
572                         cel_show_user_def ? "Yes" : "No");
573         }
574
575         pgsql_reconnect();
576         if (PQstatus(conn) != CONNECTION_BAD) {
577                 char sqlcmd[768];
578                 char *fname, *ftype, *flen, *fnotnull, *fdef, *tablename, *tmp_tablename;
579                 int i, rows, version;
580
581                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
582                 connected = 1;
583
584                 version = PQserverVersion(conn);
585                 /* Remove any schema name from the table */
586                 if ((tmp_tablename = strrchr(table, '.'))) {
587                         tmp_tablename++;
588                 } else {
589                         tmp_tablename = table;
590                 }
591                 tablename = ast_alloca(strlen(tmp_tablename) * 2 + 1);
592                 PQescapeStringConn(conn, tablename, tmp_tablename, strlen(tmp_tablename), NULL);
593                 if (version >= PGSQL_MIN_VERSION_SCHEMA) {
594                         char *schemaname;
595                         int lenschema;
596                         lenschema = strlen(schema);
597                         schemaname = ast_alloca(lenschema * 2 + 1);
598                         PQescapeStringConn(conn, schemaname, schema, lenschema, NULL);
599
600                         snprintf(sqlcmd, sizeof(sqlcmd),
601                         "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod "
602                         "FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
603                                  "AND c.relname = '%s' AND n.nspname = %s%s%s) "
604                                "INNER JOIN pg_catalog.pg_attribute a ON ("
605                                    "NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) "
606                             "INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) "
607                         "LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid "
608                           "AND d.adnum = a.attnum "
609                         "ORDER BY n.nspname, c.relname, attnum",
610                                 tablename,
611                                 lenschema == 0 ? "" : "'", lenschema == 0 ? "current_schema()" : schemaname, lenschema == 0 ? "" : "'");
612                 } else {
613                         snprintf(sqlcmd, sizeof(sqlcmd),
614                         "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod "
615                         "FROM pg_class c, pg_type t, pg_attribute a "
616                         "LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid "
617                         "AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid "
618                         "AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", tablename);
619                 }
620                 /* Query the columns */
621                 result = PQexec(conn, sqlcmd);
622                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
623                         pgerror = PQresultErrorMessage(result);
624                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
625                         PQclear(result);
626                         unload_module();
627                         return AST_MODULE_LOAD_DECLINE;
628                 }
629
630                 rows = PQntuples(result);
631                 for (i = 0; i < rows; i++) {
632                         fname = PQgetvalue(result, i, 0);
633                         ftype = PQgetvalue(result, i, 1);
634                         flen = PQgetvalue(result, i, 2);
635                         fnotnull = PQgetvalue(result, i, 3);
636                         fdef = PQgetvalue(result, i, 4);
637                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
638                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
639                         if (cur) {
640                                 sscanf(flen, "%30d", &cur->len);
641                                 cur->name = (char *)cur + sizeof(*cur);
642                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
643                                 strcpy(cur->name, fname);
644                                 strcpy(cur->type, ftype);
645                                 if (*fnotnull == 't') {
646                                         cur->notnull = 1;
647                                 } else {
648                                         cur->notnull = 0;
649                                 }
650                                 if (!ast_strlen_zero(fdef)) {
651                                         cur->hasdefault = 1;
652                                 } else {
653                                         cur->hasdefault = 0;
654                                 }
655                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
656                         }
657                 }
658                 PQclear(result);
659         } else {
660                 pgerror = PQerrorMessage(conn);
661                 ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
662                 ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
663                 connected = 0;
664                 PQfinish(conn);
665                 conn = NULL;
666         }
667         return AST_MODULE_LOAD_SUCCESS;
668 }
669
670 static int my_load_module(int reload)
671 {
672         struct ast_config *cfg;
673         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
674
675         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
676                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CEL's: %s\n", config);
677                 return AST_MODULE_LOAD_DECLINE;
678         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
679                 return AST_MODULE_LOAD_SUCCESS;
680         }
681
682         if (reload) {
683                 my_unload_module();
684         }
685
686         process_my_load_module(cfg);
687         ast_config_destroy(cfg);
688
689         if (ast_cel_backend_register(PGSQL_BACKEND_NAME, pgsql_log)) {
690                 ast_log(LOG_WARNING, "Unable to subscribe to CEL events for pgsql\n");
691                 return AST_MODULE_LOAD_DECLINE;
692         }
693
694         return AST_MODULE_LOAD_SUCCESS;
695 }
696
697 static int load_module(void)
698 {
699         return my_load_module(0);
700 }
701
702 static int reload(void)
703 {
704         return my_load_module(1);
705 }
706
707 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CEL Backend",
708         .support_level = AST_MODULE_SUPPORT_EXTENDED,
709         .load = load_module,
710         .unload = unload_module,
711         .reload = reload,
712         .load_pri = AST_MODPRI_CDR_DRIVER,
713 );