Avoid cppcheck warnings; removing unused vars and a bit of cleanup.
[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         char *pgerror;
452         struct columns *cur;
453         PGresult *result;
454         const char *tmp;
455         struct ast_config *cfg;
456         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
457
458         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
459                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
460                 return -1;
461         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
462                 return 0;
463         }
464
465         ast_mutex_lock(&pgsql_lock);
466
467         if (!ast_variable_browse(cfg, "global")) {
468                 ast_config_destroy(cfg);
469                 ast_mutex_unlock(&pgsql_lock);
470                 ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
471                         reload ? "reload" : "load");
472                 return -1;
473         }
474
475         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
476                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
477                 tmp = "";       /* connect via UNIX-socket by default */
478         }
479
480         ast_free(pghostname);
481         if (!(pghostname = ast_strdup(tmp))) {
482                 ast_config_destroy(cfg);
483                 ast_mutex_unlock(&pgsql_lock);
484                 return -1;
485         }
486
487         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
488                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
489                 tmp = "asteriskcdrdb";
490         }
491
492         ast_free(pgdbname);
493         if (!(pgdbname = ast_strdup(tmp))) {
494                 ast_config_destroy(cfg);
495                 ast_mutex_unlock(&pgsql_lock);
496                 return -1;
497         }
498
499         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
500                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
501                 tmp = "asterisk";
502         }
503
504         ast_free(pgdbuser);
505         if (!(pgdbuser = ast_strdup(tmp))) {
506                 ast_config_destroy(cfg);
507                 ast_mutex_unlock(&pgsql_lock);
508                 return -1;
509         }
510
511         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
512                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
513                 tmp = "";
514         }
515
516         ast_free(pgpassword);
517         if (!(pgpassword = ast_strdup(tmp))) {
518                 ast_config_destroy(cfg);
519                 ast_mutex_unlock(&pgsql_lock);
520                 return -1;
521         }
522
523         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
524                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
525                 tmp = "5432";
526         }
527
528         ast_free(pgdbport);
529         if (!(pgdbport = ast_strdup(tmp))) {
530                 ast_config_destroy(cfg);
531                 ast_mutex_unlock(&pgsql_lock);
532                 return -1;
533         }
534
535         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
536                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
537                 tmp = "cdr";
538         }
539
540         ast_free(table);
541         if (!(table = ast_strdup(tmp))) {
542                 ast_config_destroy(cfg);
543                 ast_mutex_unlock(&pgsql_lock);
544                 return -1;
545         }
546
547         if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
548                 ast_log(LOG_WARNING, "Encoding not specified.  Assuming LATIN9\n");
549                 tmp = "LATIN9";
550         }
551
552         ast_free(encoding);
553         if (!(encoding = ast_strdup(tmp))) {
554                 ast_config_destroy(cfg);
555                 ast_mutex_unlock(&pgsql_lock);
556                 return -1;
557         }
558
559         if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
560                 tmp = "";
561         }
562
563         ast_free(tz);
564         tz = NULL;
565
566         if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
567                 ast_config_destroy(cfg);
568                 ast_mutex_unlock(&pgsql_lock);
569                 return -1;
570         }
571
572         if (option_debug) {
573                 if (ast_strlen_zero(pghostname)) {
574                         ast_debug(1, "using default unix socket\n");
575                 } else {
576                         ast_debug(1, "got hostname of %s\n", pghostname);
577                 }
578                 ast_debug(1, "got port of %s\n", pgdbport);
579                 ast_debug(1, "got user of %s\n", pgdbuser);
580                 ast_debug(1, "got dbname of %s\n", pgdbname);
581                 ast_debug(1, "got password of %s\n", pgpassword);
582                 ast_debug(1, "got sql table name of %s\n", table);
583                 ast_debug(1, "got encoding of %s\n", encoding);
584                 ast_debug(1, "got timezone of %s\n", tz);
585         }
586
587         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
588         if (PQstatus(conn) != CONNECTION_BAD) {
589                 char sqlcmd[768];
590                 char *fname, *ftype, *flen, *fnotnull, *fdef;
591                 int i, rows, version;
592                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
593                 connected = 1;
594                 connect_time = time(NULL);
595                 records = 0;
596                 if (PQsetClientEncoding(conn, encoding)) {
597 #ifdef HAVE_PGSQL_pg_encoding_to_char
598                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
599 #else
600                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
601 #endif
602                 }
603                 version = PQserverVersion(conn);
604
605                 if (version >= 70300) {
606                         char *schemaname, *tablename;
607                         if (strchr(table, '.')) {
608                                 schemaname = ast_strdupa(table);
609                                 tablename = strchr(schemaname, '.');
610                                 *tablename++ = '\0';
611                         } else {
612                                 schemaname = "";
613                                 tablename = table;
614                         }
615
616                         /* Escape special characters in schemaname */
617                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
618                                 char *tmp = schemaname, *ptr;
619
620                                 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
621                                 for (; *tmp; tmp++) {
622                                         if (strchr("\\'", *tmp)) {
623                                                 *ptr++ = *tmp;
624                                         }
625                                         *ptr++ = *tmp;
626                                 }
627                                 *ptr = '\0';
628                         }
629                         /* Escape special characters in tablename */
630                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
631                                 char *tmp = tablename, *ptr;
632
633                                 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
634                                 for (; *tmp; tmp++) {
635                                         if (strchr("\\'", *tmp)) {
636                                                 *ptr++ = *tmp;
637                                         }
638                                         *ptr++ = *tmp;
639                                 }
640                                 *ptr = '\0';
641                         }
642
643                         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",
644                                 tablename,
645                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
646                 } else {
647                         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);
648                 }
649                 /* Query the columns */
650                 result = PQexec(conn, sqlcmd);
651                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
652                         pgerror = PQresultErrorMessage(result);
653                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
654                         PQclear(result);
655                         unload_module();
656                         ast_mutex_unlock(&pgsql_lock);
657                         return AST_MODULE_LOAD_DECLINE;
658                 }
659
660                 rows = PQntuples(result);
661                 if (rows == 0) {
662                         ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
663                         PQclear(result);
664                         unload_module();
665                         ast_mutex_unlock(&pgsql_lock);
666                         return AST_MODULE_LOAD_DECLINE;
667                 }
668
669                 /* Clear out the columns list. */
670                 empty_columns();
671
672                 for (i = 0; i < rows; i++) {
673                         fname = PQgetvalue(result, i, 0);
674                         ftype = PQgetvalue(result, i, 1);
675                         flen = PQgetvalue(result, i, 2);
676                         fnotnull = PQgetvalue(result, i, 3);
677                         fdef = PQgetvalue(result, i, 4);
678                         if (atoi(flen) == -1) {
679                                 /* For varchar columns, the maximum length is encoded in a different field */
680                                 flen = PQgetvalue(result, i, 5);
681                         }
682                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
683                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
684                         if (cur) {
685                                 sscanf(flen, "%30d", &cur->len);
686                                 cur->name = (char *)cur + sizeof(*cur);
687                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
688                                 strcpy(cur->name, fname);
689                                 strcpy(cur->type, ftype);
690                                 if (*fnotnull == 't') {
691                                         cur->notnull = 1;
692                                 } else {
693                                         cur->notnull = 0;
694                                 }
695                                 if (!ast_strlen_zero(fdef)) {
696                                         cur->hasdefault = 1;
697                                 } else {
698                                         cur->hasdefault = 0;
699                                 }
700                                 AST_RWLIST_WRLOCK(&psql_columns);
701                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
702                                 AST_RWLIST_UNLOCK(&psql_columns);
703                         }
704                 }
705                 PQclear(result);
706         } else {
707                 pgerror = PQerrorMessage(conn);
708                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
709                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
710                 connected = 0;
711         }
712
713         ast_config_destroy(cfg);
714
715         ast_mutex_unlock(&pgsql_lock);
716         return 0;
717 }
718
719 static int load_module(void)
720 {
721         ast_cli_register_multiple(cdr_pgsql_status_cli, sizeof(cdr_pgsql_status_cli) / sizeof(struct ast_cli_entry));
722         if (config_module(0)) {
723                 return AST_MODULE_LOAD_DECLINE;
724         }
725         return ast_cdr_register(name, ast_module_info->description, pgsql_log)
726                 ? AST_MODULE_LOAD_DECLINE : 0;
727 }
728
729 static int reload(void)
730 {
731         return config_module(1);
732 }
733
734 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
735                 .load = load_module,
736                 .unload = unload_module,
737                 .reload = reload,
738                 .load_pri = AST_MODPRI_CDR_DRIVER,
739                );