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