Fix the ability to specify an OSP token for an outbound IAX2 call.
[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 /*! \file
24  *
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 <time.h>
45
46 #include <libpq-fe.h>
47
48 #include "asterisk/config.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/cdr.h"
51 #include "asterisk/module.h"
52
53 #define DATE_FORMAT "'%Y-%m-%d %T'"
54
55 static char *name = "pgsql";
56 static char *config = "cdr_pgsql.conf";
57 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
58 static int connected = 0;
59 static int maxsize = 512, maxsize2 = 512;
60
61 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
62
63 static PGconn   *conn = NULL;
64
65 struct columns {
66         char *name;
67         char *type;
68         int len;
69         unsigned int notnull:1;
70         unsigned int hasdefault:1;
71         AST_RWLIST_ENTRY(columns) list;
72 };
73
74 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
75
76 #define LENGTHEN_BUF1(size)                                               \
77                         do {                                                          \
78                                 /* Lengthen buffer, if necessary */                       \
79                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
80                                         if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) {  \
81                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n"); \
82                                                 ast_free(sql);                                    \
83                                                 ast_free(sql2);                                   \
84                                                 AST_RWLIST_UNLOCK(&psql_columns);                 \
85                                                 return -1;                                        \
86                                         }                                                     \
87                                 }                                                         \
88                         } while (0)
89
90 #define LENGTHEN_BUF2(size)                               \
91                         do {                                          \
92                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {  \
93                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) {        \
94                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n");      \
95                                                 ast_free(sql);                    \
96                                                 ast_free(sql2);                   \
97                                                 AST_RWLIST_UNLOCK(&psql_columns); \
98                                                 return -1;                        \
99                                         }                                     \
100                                 }                                         \
101                         } while (0)
102
103 static int pgsql_log(struct ast_cdr *cdr)
104 {
105         struct ast_tm tm;
106         char *pgerror;
107         PGresult *result;
108
109         ast_mutex_lock(&pgsql_lock);
110
111         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
112                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
113                 if (PQstatus(conn) != CONNECTION_BAD) {
114                         connected = 1;
115                 } else {
116                         pgerror = PQerrorMessage(conn);
117                         ast_log(LOG_ERROR, "Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
118                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
119                         PQfinish(conn);
120                         conn = NULL;
121                 }
122         }
123
124         if (connected) {
125                 struct columns *cur;
126                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
127                 char buf[257], escapebuf[513], *value;
128                 int first = 1;
129   
130                 if (!sql || !sql2) {
131                         if (sql) {
132                                 ast_free(sql);
133                         }
134                         if (sql2) {
135                                 ast_free(sql2);
136                         }
137                         return -1;
138                 }
139
140                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
141                 ast_str_set(&sql2, 0, " VALUES (");
142
143                 AST_RWLIST_RDLOCK(&psql_columns);
144                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
145                         /* For fields not set, simply skip them */
146                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
147                         if (strcmp(cur->name, "calldate") == 0 && !value) {
148                                 ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 0);
149                         }
150                         if (!value) {
151                                 if (cur->notnull && !cur->hasdefault) {
152                                         /* Field is NOT NULL (but no default), must include it anyway */
153                                         LENGTHEN_BUF1(strlen(cur->name) + 2);
154                                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
155                                         LENGTHEN_BUF2(3);
156                                         ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
157                                         first = 0;
158                                 }
159                                 continue;
160                         }
161
162                         LENGTHEN_BUF1(strlen(cur->name) + 2);
163                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
164
165                         if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
166                                 if (strncmp(cur->type, "int", 3) == 0) {
167                                         LENGTHEN_BUF2(13);
168                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", cdr->start.tv_sec);
169                                 } else if (strncmp(cur->type, "float", 5) == 0) {
170                                         LENGTHEN_BUF2(31);
171                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
172                                 } else {
173                                         /* char, hopefully */
174                                         LENGTHEN_BUF2(31);
175                                         ast_localtime(&cdr->start, &tm, NULL);
176                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
177                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
178                                 }
179                         } else if (strcmp(cur->name, "answer") == 0) {
180                                 if (strncmp(cur->type, "int", 3) == 0) {
181                                         LENGTHEN_BUF2(13);
182                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", cdr->answer.tv_sec);
183                                 } else if (strncmp(cur->type, "float", 5) == 0) {
184                                         LENGTHEN_BUF2(31);
185                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
186                                 } else {
187                                         /* char, hopefully */
188                                         LENGTHEN_BUF2(31);
189                                         ast_localtime(&cdr->start, &tm, NULL);
190                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
191                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
192                                 }
193                         } else if (strcmp(cur->name, "end") == 0) {
194                                 if (strncmp(cur->type, "int", 3) == 0) {
195                                         LENGTHEN_BUF2(13);
196                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", cdr->end.tv_sec);
197                                 } else if (strncmp(cur->type, "float", 5) == 0) {
198                                         LENGTHEN_BUF2(31);
199                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
200                                 } else {
201                                         /* char, hopefully */
202                                         LENGTHEN_BUF2(31);
203                                         ast_localtime(&cdr->end, &tm, NULL);
204                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
205                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
206                                 }
207                         } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
208                                 if (cur->type[0] == 'i') {
209                                         /* Get integer, no need to escape anything */
210                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
211                                         LENGTHEN_BUF2(13);
212                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
213                                 } else if (strncmp(cur->type, "float", 5) == 0) {
214                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
215                                         LENGTHEN_BUF2(31);
216                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec - when->tv_sec + cdr->end.tv_usec / 1000000.0 - when->tv_usec / 1000000.0);
217                                 } else {
218                                         /* Char field, probably */
219                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
220                                         LENGTHEN_BUF2(31);
221                                         ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double)cdr->end.tv_sec - when->tv_sec + cdr->end.tv_usec / 1000000.0 - when->tv_usec / 1000000.0);
222                                 }
223                         } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
224                                 if (strncmp(cur->type, "int", 3) == 0) {
225                                         /* Integer, no need to escape anything */
226                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
227                                         LENGTHEN_BUF2(13);
228                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
229                                 } else {
230                                         /* Although this is a char field, there are no special characters in the values for these fields */
231                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
232                                         LENGTHEN_BUF2(31);
233                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
234                                 }
235                         } else {
236                                 /* Arbitrary field, could be anything */
237                                 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
238                                 if (strncmp(cur->type, "int", 3) == 0) {
239                                         long long whatever;
240                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
241                                                 LENGTHEN_BUF2(26);
242                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
243                                         } else {
244                                                 LENGTHEN_BUF2(2);
245                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
246                                         }
247                                 } else if (strncmp(cur->type, "float", 5) == 0) {
248                                         long double whatever;
249                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
250                                                 LENGTHEN_BUF2(51);
251                                                 ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
252                                         } else {
253                                                 LENGTHEN_BUF2(2);
254                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
255                                         }
256                                 /* XXX Might want to handle dates, times, and other misc fields here XXX */
257                                 } else {
258                                         if (value)
259                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
260                                         else
261                                                 escapebuf[0] = '\0';
262                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
263                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
264                                 }
265                         }
266                         first = 0;
267                 }
268                 AST_RWLIST_UNLOCK(&psql_columns);
269                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
270                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
271                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
272
273                 ast_debug(2, "inserting a CDR record.\n");
274
275                 /* Test to be sure we're still connected... */
276                 /* If we're connected, and connection is working, good. */
277                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
278                 if (PQstatus(conn) == CONNECTION_OK) {
279                         connected = 1;
280                 } else {
281                         ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
282                         PQreset(conn);
283                         if (PQstatus(conn) == CONNECTION_OK) {
284                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
285                                 connected = 1;
286                         } else {
287                                 pgerror = PQerrorMessage(conn);
288                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
289                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
290                                 PQfinish(conn);
291                                 conn = NULL;
292                                 connected = 0;
293                                 ast_mutex_unlock(&pgsql_lock);
294                                 ast_free(sql);
295                                 ast_free(sql2);
296                                 return -1;
297                         }
298                 }
299                 result = PQexec(conn, ast_str_buffer(sql));
300                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
301                         pgerror = PQresultErrorMessage(result);
302                         ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
303                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
304                         ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
305                         PQreset(conn);
306                         if (PQstatus(conn) == CONNECTION_OK) {
307                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
308                                 connected = 1;
309                                 PQclear(result);
310                                 result = PQexec(conn, ast_str_buffer(sql));
311                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
312                                         pgerror = PQresultErrorMessage(result);
313                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
314                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
315                                 }
316                         }
317                         ast_mutex_unlock(&pgsql_lock);
318                         PQclear(result);
319                         ast_free(sql);
320                         ast_free(sql2);
321                         return -1;
322                 }
323                 PQclear(result);
324                 ast_free(sql);
325                 ast_free(sql2);
326         }
327         ast_mutex_unlock(&pgsql_lock);
328         return 0;
329 }
330
331 static int unload_module(void)
332 {
333         struct columns *current;
334
335         ast_cdr_unregister(name);
336
337         PQfinish(conn);
338
339         if (pghostname)
340                 ast_free(pghostname);
341         if (pgdbname)
342                 ast_free(pgdbname);
343         if (pgdbuser)
344                 ast_free(pgdbuser);
345         if (pgpassword)
346                 ast_free(pgpassword);
347         if (pgdbport)
348                 ast_free(pgdbport);
349         if (table)
350                 ast_free(table);
351
352         AST_RWLIST_WRLOCK(&psql_columns);
353         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
354                 ast_free(current);
355         }
356         AST_RWLIST_UNLOCK(&psql_columns);
357
358         return 0;
359 }
360
361 static int config_module(int reload)
362 {
363         struct ast_variable *var;
364         char *pgerror;
365         struct columns *cur;
366         PGresult *result;
367         const char *tmp;
368         struct ast_config *cfg;
369         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
370
371         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
372                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
373                 return -1;
374         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
375                 return 0;
376
377         if (!(var = ast_variable_browse(cfg, "global"))) {
378                 ast_config_destroy(cfg);
379                 return 0;
380         }
381
382         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
383                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
384                 tmp = "";       /* connect via UNIX-socket by default */
385         }
386
387         if (pghostname)
388                 ast_free(pghostname);
389         if (!(pghostname = ast_strdup(tmp))) {
390                 ast_config_destroy(cfg);
391                 return -1;
392         }
393
394         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
395                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
396                 tmp = "asteriskcdrdb";
397         }
398
399         if (pgdbname)
400                 ast_free(pgdbname);
401         if (!(pgdbname = ast_strdup(tmp))) {
402                 ast_config_destroy(cfg);
403                 return -1;
404         }
405
406         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
407                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
408                 tmp = "asterisk";
409         }
410
411         if (pgdbuser)
412                 ast_free(pgdbuser);
413         if (!(pgdbuser = ast_strdup(tmp))) {
414                 ast_config_destroy(cfg);
415                 return -1;
416         }
417
418         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
419                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
420                 tmp = "";
421         }
422
423         if (pgpassword)
424                 ast_free(pgpassword);
425         if (!(pgpassword = ast_strdup(tmp))) {
426                 ast_config_destroy(cfg);
427                 return -1;
428         }
429
430         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
431                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
432                 tmp = "5432";
433         }
434
435         if (pgdbport)
436                 ast_free(pgdbport);
437         if (!(pgdbport = ast_strdup(tmp))) {
438                 ast_config_destroy(cfg);
439                 return -1;
440         }
441
442         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
443                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
444                 tmp = "cdr";
445         }
446
447         if (table)
448                 ast_free(table);
449         if (!(table = ast_strdup(tmp))) {
450                 ast_config_destroy(cfg);
451                 return -1;
452         }
453
454         if (option_debug) {
455                 if (ast_strlen_zero(pghostname)) {
456                         ast_debug(1, "using default unix socket\n");
457                 } else {
458                         ast_debug(1, "got hostname of %s\n", pghostname);
459                 }
460                 ast_debug(1, "got port of %s\n", pgdbport);
461                 ast_debug(1, "got user of %s\n", pgdbuser);
462                 ast_debug(1, "got dbname of %s\n", pgdbname);
463                 ast_debug(1, "got password of %s\n", pgpassword);
464                 ast_debug(1, "got sql table name of %s\n", table);
465         }
466
467         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
468         if (PQstatus(conn) != CONNECTION_BAD) {
469                 char sqlcmd[768];
470                 char *fname, *ftype, *flen, *fnotnull, *fdef;
471                 int i, rows, version;
472                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
473                 connected = 1;
474                 version = PQserverVersion(conn);
475
476                 if (version >= 70300) {
477                         char *schemaname, *tablename;
478                         if (strchr(table, '.')) {
479                                 schemaname = ast_strdupa(table);
480                                 tablename = strchr(schemaname, '.');
481                                 *tablename++ = '\0';
482                         } else {
483                                 schemaname = "";
484                                 tablename = table;
485                         }
486
487                         /* Escape special characters in schemaname */
488                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
489                                 char *tmp = schemaname, *ptr;
490
491                                 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
492                                 for (; *tmp; tmp++) {
493                                         if (strchr("\\'", *tmp)) {
494                                                 *ptr++ = *tmp;
495                                         }
496                                         *ptr++ = *tmp;
497                                 }
498                                 *ptr = '\0';
499                         }
500                         /* Escape special characters in tablename */
501                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
502                                 char *tmp = tablename, *ptr;
503
504                                 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
505                                 for (; *tmp; tmp++) {
506                                         if (strchr("\\'", *tmp)) {
507                                                 *ptr++ = *tmp;
508                                         }
509                                         *ptr++ = *tmp;
510                                 }
511                                 *ptr = '\0';
512                         }
513
514                         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",
515                                 tablename,
516                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
517                 } else {
518                         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);
519                 }
520                 /* Query the columns */
521                 result = PQexec(conn, sqlcmd);
522                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
523                         pgerror = PQresultErrorMessage(result);
524                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
525                         PQclear(result);
526                         unload_module();
527                         return AST_MODULE_LOAD_DECLINE;
528                 }
529
530                 rows = PQntuples(result);
531                 for (i = 0; i < rows; i++) {
532                         fname = PQgetvalue(result, i, 0);
533                         ftype = PQgetvalue(result, i, 1);
534                         flen = PQgetvalue(result, i, 2);
535                         fnotnull = PQgetvalue(result, i, 3);
536                         fdef = PQgetvalue(result, i, 4);
537                         if (atoi(flen) == -1) {
538                                 /* For varchar columns, the maximum length is encoded in a different field */
539                                 flen = PQgetvalue(result, i, 5);
540                         }
541                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
542                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
543                         if (cur) {
544                                 sscanf(flen, "%30d", &cur->len);
545                                 cur->name = (char *)cur + sizeof(*cur);
546                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
547                                 strcpy(cur->name, fname);
548                                 strcpy(cur->type, ftype);
549                                 if (*fnotnull == 't') {
550                                         cur->notnull = 1;
551                                 } else {
552                                         cur->notnull = 0;
553                                 }
554                                 if (!ast_strlen_zero(fdef)) {
555                                         cur->hasdefault = 1;
556                                 } else {
557                                         cur->hasdefault = 0;
558                                 }
559                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
560                         }
561                 }
562                 PQclear(result);
563         } else {
564                 pgerror = PQerrorMessage(conn);
565                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
566                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
567                 connected = 0;
568         }
569
570         ast_config_destroy(cfg);
571
572         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
573 }
574
575 static int load_module(void)
576 {
577         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
578 }
579
580 static int reload(void)
581 {
582         return config_module(1);
583 }
584
585 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
586                 .load = load_module,
587                 .unload = unload_module,
588                 .reload = reload,
589                );