Fix column duplication bug in module reload for cdr_pgsql.
[asterisk/asterisk.git] / cdr / cdr_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003 - 2012
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         <support_level>extended</support_level>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 #include <libpq-fe.h>
46
47 #include "asterisk/config.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/cdr.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/module.h"
52
53 #define DATE_FORMAT "'%Y-%m-%d %T'"
54
55 static const char name[] = "pgsql";
56 static const char config[] = "cdr_pgsql.conf";
57 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL, *encoding = NULL, *tz = NULL;
58 static int connected = 0;
59 static int maxsize = 512, maxsize2 = 512;
60 static time_t connect_time = 0;
61 static int totalrecords = 0;
62 static int records;
63
64 static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
65 static struct ast_cli_entry cdr_pgsql_status_cli[] = {
66         AST_CLI_DEFINE(handle_cdr_pgsql_status, "Show connection status of the PostgreSQL CDR driver (cdr_pgsql)"),
67 };
68
69 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
70
71 static PGconn   *conn = NULL;
72
73 struct columns {
74         char *name;
75         char *type;
76         int len;
77         unsigned int notnull:1;
78         unsigned int hasdefault:1;
79         AST_RWLIST_ENTRY(columns) list;
80 };
81
82 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
83
84 #define LENGTHEN_BUF1(size)                                               \
85                         do {                                                          \
86                                 /* Lengthen buffer, if necessary */                       \
87                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
88                                         if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) {  \
89                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n"); \
90                                                 ast_free(sql);                                    \
91                                                 ast_free(sql2);                                   \
92                                                 AST_RWLIST_UNLOCK(&psql_columns);                 \
93                                                 ast_mutex_unlock(&pgsql_lock);                    \
94                                                 return -1;                                        \
95                                         }                                                     \
96                                 }                                                         \
97                         } while (0)
98
99 #define LENGTHEN_BUF2(size)                               \
100                         do {                                          \
101                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {  \
102                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) {        \
103                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n");      \
104                                                 ast_free(sql);                    \
105                                                 ast_free(sql2);                   \
106                                                 AST_RWLIST_UNLOCK(&psql_columns); \
107                                                 ast_mutex_unlock(&pgsql_lock);    \
108                                                 return -1;                        \
109                                         }                                     \
110                                 }                                         \
111                         } while (0)
112
113 /*! \brief Handle the CLI command cdr show pgsql status */
114 static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
115 {
116         switch (cmd) {
117         case CLI_INIT:
118                 e->command = "cdr show pgsql status";
119                 e->usage =
120                         "Usage: cdr show pgsql status\n"
121                         "       Shows current connection status for cdr_pgsql\n";
122                 return NULL;
123         case CLI_GENERATE:
124                 return NULL;
125         }
126
127         if (a->argc != 3)
128                 return CLI_SHOWUSAGE;
129
130         if (connected) {
131                 char status[256], status2[100] = "";
132                 int ctime = time(NULL) - connect_time;
133
134                 if (pgdbport) {
135                         snprintf(status, 255, "Connected to %s@%s, port %s", pgdbname, pghostname, pgdbport);
136                 } else {
137                         snprintf(status, 255, "Connected to %s@%s", pgdbname, pghostname);
138                 }
139
140                 if (pgdbuser && *pgdbuser) {
141                         snprintf(status2, 99, " with username %s", pgdbuser);
142                 }
143                 if (table && *table) {
144                         snprintf(status2, 99, " using table %s", table);
145                 }
146                 if (ctime > 31536000) {
147                         ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 31536000, (ctime % 31536000) / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
148                 } else if (ctime > 86400) {
149                         ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
150                 } else if (ctime > 3600) {
151                         ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 3600, (ctime % 3600) / 60, ctime % 60);
152                 } else if (ctime > 60) {
153                         ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60, ctime % 60);
154                 } else {
155                         ast_cli(a->fd, "%s%s for %d seconds.\n", status, status2, ctime);
156                 }
157                 if (records == totalrecords) {
158                         ast_cli(a->fd, "  Wrote %d records since last restart.\n", totalrecords);
159                 } else {
160                         ast_cli(a->fd, "  Wrote %d records since last restart and %d records since last reconnect.\n", totalrecords, records);
161                 }
162         } else {
163                 ast_cli(a->fd, "Not currently connected to a PgSQL server.\n");
164         }
165         return CLI_SUCCESS;
166 }
167
168 static int pgsql_log(struct ast_cdr *cdr)
169 {
170         struct ast_tm tm;
171         char *pgerror;
172         PGresult *result;
173
174         ast_mutex_lock(&pgsql_lock);
175
176         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
177                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
178                 if (PQstatus(conn) != CONNECTION_BAD) {
179                         connected = 1;
180                         connect_time = time(NULL);
181                         records = 0;
182                         if (PQsetClientEncoding(conn, encoding)) {
183 #ifdef HAVE_PGSQL_pg_encoding_to_char
184                                 ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
185 #else
186                                 ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
187 #endif
188                         }
189                 } else {
190                         pgerror = PQerrorMessage(conn);
191                         ast_log(LOG_ERROR, "Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
192                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
193                         PQfinish(conn);
194                         conn = NULL;
195                 }
196         }
197
198         if (connected) {
199                 struct columns *cur;
200                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
201                 char buf[257], escapebuf[513], *value;
202                 int first = 1;
203
204                 if (!sql || !sql2) {
205                         ast_free(sql);
206                         ast_free(sql2);
207                         return -1;
208                 }
209
210                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
211                 ast_str_set(&sql2, 0, " VALUES (");
212
213                 AST_RWLIST_RDLOCK(&psql_columns);
214                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
215                         /* For fields not set, simply skip them */
216                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
217                         if (strcmp(cur->name, "calldate") == 0 && !value) {
218                                 ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 0);
219                         }
220                         if (!value) {
221                                 if (cur->notnull && !cur->hasdefault) {
222                                         /* Field is NOT NULL (but no default), must include it anyway */
223                                         LENGTHEN_BUF1(strlen(cur->name) + 2);
224                                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
225                                         LENGTHEN_BUF2(3);
226                                         ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
227                                         first = 0;
228                                 }
229                                 continue;
230                         }
231
232                         LENGTHEN_BUF1(strlen(cur->name) + 2);
233                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
234
235                         if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
236                                 if (strncmp(cur->type, "int", 3) == 0) {
237                                         LENGTHEN_BUF2(13);
238                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
239                                 } else if (strncmp(cur->type, "float", 5) == 0) {
240                                         LENGTHEN_BUF2(31);
241                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
242                                 } else {
243                                         /* char, hopefully */
244                                         LENGTHEN_BUF2(31);
245                                         ast_localtime(&cdr->start, &tm, tz);
246                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
247                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
248                                 }
249                         } else if (strcmp(cur->name, "answer") == 0) {
250                                 if (strncmp(cur->type, "int", 3) == 0) {
251                                         LENGTHEN_BUF2(13);
252                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
253                                 } else if (strncmp(cur->type, "float", 5) == 0) {
254                                         LENGTHEN_BUF2(31);
255                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
256                                 } else {
257                                         /* char, hopefully */
258                                         LENGTHEN_BUF2(31);
259                                         ast_localtime(&cdr->answer, &tm, tz);
260                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
261                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
262                                 }
263                         } else if (strcmp(cur->name, "end") == 0) {
264                                 if (strncmp(cur->type, "int", 3) == 0) {
265                                         LENGTHEN_BUF2(13);
266                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
267                                 } else if (strncmp(cur->type, "float", 5) == 0) {
268                                         LENGTHEN_BUF2(31);
269                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
270                                 } else {
271                                         /* char, hopefully */
272                                         LENGTHEN_BUF2(31);
273                                         ast_localtime(&cdr->end, &tm, tz);
274                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
275                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
276                                 }
277                         } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
278                                 if (cur->type[0] == 'i') {
279                                         /* Get integer, no need to escape anything */
280                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
281                                         LENGTHEN_BUF2(13);
282                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
283                                 } else if (strncmp(cur->type, "float", 5) == 0) {
284                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
285                                         LENGTHEN_BUF2(31);
286                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
287                                 } else {
288                                         /* Char field, probably */
289                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
290                                         LENGTHEN_BUF2(31);
291                                         ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
292                                 }
293                         } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
294                                 if (strncmp(cur->type, "int", 3) == 0) {
295                                         /* Integer, no need to escape anything */
296                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
297                                         LENGTHEN_BUF2(13);
298                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
299                                 } else {
300                                         /* Although this is a char field, there are no special characters in the values for these fields */
301                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
302                                         LENGTHEN_BUF2(31);
303                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
304                                 }
305                         } else {
306                                 /* Arbitrary field, could be anything */
307                                 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
308                                 if (strncmp(cur->type, "int", 3) == 0) {
309                                         long long whatever;
310                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
311                                                 LENGTHEN_BUF2(26);
312                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
313                                         } else {
314                                                 LENGTHEN_BUF2(2);
315                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
316                                         }
317                                 } else if (strncmp(cur->type, "float", 5) == 0) {
318                                         long double whatever;
319                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
320                                                 LENGTHEN_BUF2(51);
321                                                 ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
322                                         } else {
323                                                 LENGTHEN_BUF2(2);
324                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
325                                         }
326                                 /* XXX Might want to handle dates, times, and other misc fields here XXX */
327                                 } else {
328                                         if (value)
329                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
330                                         else
331                                                 escapebuf[0] = '\0';
332                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
333                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
334                                 }
335                         }
336                         first = 0;
337                 }
338
339                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
340                 AST_RWLIST_UNLOCK(&psql_columns);
341                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
342                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
343
344                 ast_debug(2, "inserting a CDR record.\n");
345
346                 /* Test to be sure we're still connected... */
347                 /* If we're connected, and connection is working, good. */
348                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
349                 if (PQstatus(conn) == CONNECTION_OK) {
350                         connected = 1;
351                 } else {
352                         ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
353                         PQreset(conn);
354                         if (PQstatus(conn) == CONNECTION_OK) {
355                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
356                                 connected = 1;
357                                 connect_time = time(NULL);
358                                 records = 0;
359                         } else {
360                                 pgerror = PQerrorMessage(conn);
361                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
362                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
363                                 PQfinish(conn);
364                                 conn = NULL;
365                                 connected = 0;
366                                 ast_mutex_unlock(&pgsql_lock);
367                                 ast_free(sql);
368                                 ast_free(sql2);
369                                 return -1;
370                         }
371                 }
372                 result = PQexec(conn, ast_str_buffer(sql));
373                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
374                         pgerror = PQresultErrorMessage(result);
375                         ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
376                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
377                         ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
378                         PQreset(conn);
379                         if (PQstatus(conn) == CONNECTION_OK) {
380                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
381                                 connected = 1;
382                                 connect_time = time(NULL);
383                                 records = 0;
384                                 PQclear(result);
385                                 result = PQexec(conn, ast_str_buffer(sql));
386                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
387                                         pgerror = PQresultErrorMessage(result);
388                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
389                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
390                                 }  else {
391                                         /* Second try worked out ok */
392                                         totalrecords++;
393                                         records++;
394                                         ast_mutex_unlock(&pgsql_lock);
395                                         PQclear(result);
396                                         return 0;
397                                 }
398                         }
399                         ast_mutex_unlock(&pgsql_lock);
400                         PQclear(result);
401                         ast_free(sql);
402                         ast_free(sql2);
403                         return -1;
404                 } else {
405                         totalrecords++;
406                         records++;
407                 }
408                 PQclear(result);
409                 ast_free(sql);
410                 ast_free(sql2);
411         }
412         ast_mutex_unlock(&pgsql_lock);
413         return 0;
414 }
415
416 /* This function should be called without holding the pgsql_columns lock */
417 static void empty_columns(void)
418 {
419         struct columns *current;
420         AST_RWLIST_WRLOCK(&psql_columns);
421         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
422                 ast_free(current);
423         }
424         AST_RWLIST_UNLOCK(&psql_columns);
425
426 }
427
428 static int unload_module(void)
429 {
430         ast_cdr_unregister(name);
431         ast_cli_unregister_multiple(cdr_pgsql_status_cli, ARRAY_LEN(cdr_pgsql_status_cli));
432
433         PQfinish(conn);
434
435         ast_free(pghostname);
436         ast_free(pgdbname);
437         ast_free(pgdbuser);
438         ast_free(pgpassword);
439         ast_free(pgdbport);
440         ast_free(table);
441         ast_free(encoding);
442         ast_free(tz);
443
444         empty_columns();
445
446         return 0;
447 }
448
449 static int config_module(int reload)
450 {
451         struct ast_variable *var;
452         char *pgerror;
453         struct columns *cur;
454         PGresult *result;
455         const char *tmp;
456         struct ast_config *cfg;
457         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
458
459         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
460                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
461                 return -1;
462         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
463                 return 0;
464         }
465
466         ast_mutex_lock(&pgsql_lock);
467
468         if (!(var = ast_variable_browse(cfg, "global"))) {
469                 ast_config_destroy(cfg);
470                 ast_mutex_unlock(&pgsql_lock);
471                 ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
472                         reload ? "reload" : "load");
473                 return -1;
474         }
475
476         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
477                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
478                 tmp = "";       /* connect via UNIX-socket by default */
479         }
480
481         ast_free(pghostname);
482         if (!(pghostname = ast_strdup(tmp))) {
483                 ast_config_destroy(cfg);
484                 ast_mutex_unlock(&pgsql_lock);
485                 return -1;
486         }
487
488         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
489                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
490                 tmp = "asteriskcdrdb";
491         }
492
493         ast_free(pgdbname);
494         if (!(pgdbname = ast_strdup(tmp))) {
495                 ast_config_destroy(cfg);
496                 ast_mutex_unlock(&pgsql_lock);
497                 return -1;
498         }
499
500         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
501                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
502                 tmp = "asterisk";
503         }
504
505         ast_free(pgdbuser);
506         if (!(pgdbuser = ast_strdup(tmp))) {
507                 ast_config_destroy(cfg);
508                 ast_mutex_unlock(&pgsql_lock);
509                 return -1;
510         }
511
512         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
513                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
514                 tmp = "";
515         }
516
517         ast_free(pgpassword);
518         if (!(pgpassword = ast_strdup(tmp))) {
519                 ast_config_destroy(cfg);
520                 ast_mutex_unlock(&pgsql_lock);
521                 return -1;
522         }
523
524         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
525                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
526                 tmp = "5432";
527         }
528
529         ast_free(pgdbport);
530         if (!(pgdbport = ast_strdup(tmp))) {
531                 ast_config_destroy(cfg);
532                 ast_mutex_unlock(&pgsql_lock);
533                 return -1;
534         }
535
536         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
537                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
538                 tmp = "cdr";
539         }
540
541         ast_free(table);
542         if (!(table = ast_strdup(tmp))) {
543                 ast_config_destroy(cfg);
544                 ast_mutex_unlock(&pgsql_lock);
545                 return -1;
546         }
547
548         if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
549                 ast_log(LOG_WARNING, "Encoding not specified.  Assuming LATIN9\n");
550                 tmp = "LATIN9";
551         }
552
553         ast_free(encoding);
554         if (!(encoding = ast_strdup(tmp))) {
555                 ast_config_destroy(cfg);
556                 ast_mutex_unlock(&pgsql_lock);
557                 return -1;
558         }
559
560         if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
561                 tmp = "";
562         }
563
564         ast_free(tz);
565         tz = NULL;
566
567         if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
568                 ast_config_destroy(cfg);
569                 ast_mutex_unlock(&pgsql_lock);
570                 return -1;
571         }
572
573         if (option_debug) {
574                 if (ast_strlen_zero(pghostname)) {
575                         ast_debug(1, "using default unix socket\n");
576                 } else {
577                         ast_debug(1, "got hostname of %s\n", pghostname);
578                 }
579                 ast_debug(1, "got port of %s\n", pgdbport);
580                 ast_debug(1, "got user of %s\n", pgdbuser);
581                 ast_debug(1, "got dbname of %s\n", pgdbname);
582                 ast_debug(1, "got password of %s\n", pgpassword);
583                 ast_debug(1, "got sql table name of %s\n", table);
584                 ast_debug(1, "got encoding of %s\n", encoding);
585                 ast_debug(1, "got timezone of %s\n", tz);
586         }
587
588         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
589         if (PQstatus(conn) != CONNECTION_BAD) {
590                 char sqlcmd[768];
591                 char *fname, *ftype, *flen, *fnotnull, *fdef;
592                 int i, rows, version;
593                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
594                 connected = 1;
595                 connect_time = time(NULL);
596                 records = 0;
597                 if (PQsetClientEncoding(conn, encoding)) {
598 #ifdef HAVE_PGSQL_pg_encoding_to_char
599                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
600 #else
601                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
602 #endif
603                 }
604                 version = PQserverVersion(conn);
605
606                 if (version >= 70300) {
607                         char *schemaname, *tablename;
608                         if (strchr(table, '.')) {
609                                 schemaname = ast_strdupa(table);
610                                 tablename = strchr(schemaname, '.');
611                                 *tablename++ = '\0';
612                         } else {
613                                 schemaname = "";
614                                 tablename = table;
615                         }
616
617                         /* Escape special characters in schemaname */
618                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
619                                 char *tmp = schemaname, *ptr;
620
621                                 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
622                                 for (; *tmp; tmp++) {
623                                         if (strchr("\\'", *tmp)) {
624                                                 *ptr++ = *tmp;
625                                         }
626                                         *ptr++ = *tmp;
627                                 }
628                                 *ptr = '\0';
629                         }
630                         /* Escape special characters in tablename */
631                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
632                                 char *tmp = tablename, *ptr;
633
634                                 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
635                                 for (; *tmp; tmp++) {
636                                         if (strchr("\\'", *tmp)) {
637                                                 *ptr++ = *tmp;
638                                         }
639                                         *ptr++ = *tmp;
640                                 }
641                                 *ptr = '\0';
642                         }
643
644                         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",
645                                 tablename,
646                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
647                 } else {
648                         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);
649                 }
650                 /* Query the columns */
651                 result = PQexec(conn, sqlcmd);
652                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
653                         pgerror = PQresultErrorMessage(result);
654                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
655                         PQclear(result);
656                         unload_module();
657                         ast_mutex_unlock(&pgsql_lock);
658                         return AST_MODULE_LOAD_DECLINE;
659                 }
660
661                 rows = PQntuples(result);
662                 if (rows == 0) {
663                         ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
664                         PQclear(result);
665                         unload_module();
666                         ast_mutex_unlock(&pgsql_lock);
667                         return AST_MODULE_LOAD_DECLINE;
668                 }
669
670                 /* Clear out the columns list. */
671                 empty_columns();
672
673                 for (i = 0; i < rows; i++) {
674                         fname = PQgetvalue(result, i, 0);
675                         ftype = PQgetvalue(result, i, 1);
676                         flen = PQgetvalue(result, i, 2);
677                         fnotnull = PQgetvalue(result, i, 3);
678                         fdef = PQgetvalue(result, i, 4);
679                         if (atoi(flen) == -1) {
680                                 /* For varchar columns, the maximum length is encoded in a different field */
681                                 flen = PQgetvalue(result, i, 5);
682                         }
683                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
684                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
685                         if (cur) {
686                                 sscanf(flen, "%30d", &cur->len);
687                                 cur->name = (char *)cur + sizeof(*cur);
688                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
689                                 strcpy(cur->name, fname);
690                                 strcpy(cur->type, ftype);
691                                 if (*fnotnull == 't') {
692                                         cur->notnull = 1;
693                                 } else {
694                                         cur->notnull = 0;
695                                 }
696                                 if (!ast_strlen_zero(fdef)) {
697                                         cur->hasdefault = 1;
698                                 } else {
699                                         cur->hasdefault = 0;
700                                 }
701                                 AST_RWLIST_WRLOCK(&psql_columns);
702                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
703                                 AST_RWLIST_UNLOCK(&psql_columns);
704                         }
705                 }
706                 PQclear(result);
707         } else {
708                 pgerror = PQerrorMessage(conn);
709                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
710                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
711                 connected = 0;
712         }
713
714         ast_config_destroy(cfg);
715
716         ast_mutex_unlock(&pgsql_lock);
717         return 0;
718 }
719
720 static int load_module(void)
721 {
722         ast_cli_register_multiple(cdr_pgsql_status_cli, sizeof(cdr_pgsql_status_cli) / sizeof(struct ast_cli_entry));
723         if (config_module(0)) {
724                 return AST_MODULE_LOAD_DECLINE;
725         }
726         return ast_cdr_register(name, ast_module_info->description, pgsql_log)
727                 ? AST_MODULE_LOAD_DECLINE : 0;
728 }
729
730 static int reload(void)
731 {
732         return config_module(1);
733 }
734
735 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
736                 .load = load_module,
737                 .unload = unload_module,
738                 .reload = reload,
739                 .load_pri = AST_MODPRI_CDR_DRIVER,
740                );