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