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