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