Doxygen Updates - Title update
[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_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
226                         if (strcmp(cur->name, "calldate") == 0 && !value) {
227                                 ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 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_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 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_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 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_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 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_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 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                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
352
353                 ast_debug(2, "inserting a CDR record.\n");
354
355                 /* Test to be sure we're still connected... */
356                 /* If we're connected, and connection is working, good. */
357                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
358                 if (PQstatus(conn) == CONNECTION_OK) {
359                         connected = 1;
360                 } else {
361                         ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
362                         PQreset(conn);
363                         if (PQstatus(conn) == CONNECTION_OK) {
364                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
365                                 connected = 1;
366                                 connect_time = time(NULL);
367                                 records = 0;
368                         } else {
369                                 pgerror = PQerrorMessage(conn);
370                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
371                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
372                                 PQfinish(conn);
373                                 conn = NULL;
374                                 connected = 0;
375                                 ast_mutex_unlock(&pgsql_lock);
376                                 ast_free(sql);
377                                 ast_free(sql2);
378                                 return -1;
379                         }
380                 }
381                 result = PQexec(conn, ast_str_buffer(sql));
382                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
383                         pgerror = PQresultErrorMessage(result);
384                         ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
385                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
386                         ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
387                         PQreset(conn);
388                         if (PQstatus(conn) == CONNECTION_OK) {
389                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
390                                 connected = 1;
391                                 connect_time = time(NULL);
392                                 records = 0;
393                                 PQclear(result);
394                                 result = PQexec(conn, ast_str_buffer(sql));
395                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
396                                         pgerror = PQresultErrorMessage(result);
397                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
398                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
399                                 }  else {
400                                         /* Second try worked out ok */
401                                         totalrecords++;
402                                         records++;
403                                         ast_mutex_unlock(&pgsql_lock);
404                                         PQclear(result);
405                                         return 0;
406                                 }
407                         }
408                         ast_mutex_unlock(&pgsql_lock);
409                         PQclear(result);
410                         ast_free(sql);
411                         ast_free(sql2);
412                         return -1;
413                 } else {
414                         totalrecords++;
415                         records++;
416                 }
417                 PQclear(result);
418                 ast_free(sql);
419                 ast_free(sql2);
420         }
421         ast_mutex_unlock(&pgsql_lock);
422         return 0;
423 }
424
425 /* This function should be called without holding the pgsql_columns lock */
426 static void empty_columns(void)
427 {
428         struct columns *current;
429         AST_RWLIST_WRLOCK(&psql_columns);
430         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
431                 ast_free(current);
432         }
433         AST_RWLIST_UNLOCK(&psql_columns);
434
435 }
436
437 static int unload_module(void)
438 {
439         ast_cdr_unregister(name);
440         ast_cli_unregister_multiple(cdr_pgsql_status_cli, ARRAY_LEN(cdr_pgsql_status_cli));
441
442         PQfinish(conn);
443
444         ast_free(pghostname);
445         ast_free(pgdbname);
446         ast_free(pgdbuser);
447         ast_free(pgpassword);
448         ast_free(pgdbport);
449         ast_free(table);
450         ast_free(encoding);
451         ast_free(tz);
452
453         empty_columns();
454
455         return 0;
456 }
457
458 static int config_module(int reload)
459 {
460         char *pgerror;
461         struct columns *cur;
462         PGresult *result;
463         const char *tmp;
464         struct ast_config *cfg;
465         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
466
467         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
468                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
469                 return -1;
470         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
471                 return 0;
472         }
473
474         ast_mutex_lock(&pgsql_lock);
475
476         if (!ast_variable_browse(cfg, "global")) {
477                 ast_config_destroy(cfg);
478                 ast_mutex_unlock(&pgsql_lock);
479                 ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
480                         reload ? "reload" : "load");
481                 return -1;
482         }
483
484         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
485                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
486                 tmp = "";       /* connect via UNIX-socket by default */
487         }
488
489         ast_free(pghostname);
490         if (!(pghostname = ast_strdup(tmp))) {
491                 ast_config_destroy(cfg);
492                 ast_mutex_unlock(&pgsql_lock);
493                 return -1;
494         }
495
496         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
497                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
498                 tmp = "asteriskcdrdb";
499         }
500
501         ast_free(pgdbname);
502         if (!(pgdbname = ast_strdup(tmp))) {
503                 ast_config_destroy(cfg);
504                 ast_mutex_unlock(&pgsql_lock);
505                 return -1;
506         }
507
508         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
509                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
510                 tmp = "asterisk";
511         }
512
513         ast_free(pgdbuser);
514         if (!(pgdbuser = ast_strdup(tmp))) {
515                 ast_config_destroy(cfg);
516                 ast_mutex_unlock(&pgsql_lock);
517                 return -1;
518         }
519
520         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
521                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
522                 tmp = "";
523         }
524
525         ast_free(pgpassword);
526         if (!(pgpassword = ast_strdup(tmp))) {
527                 ast_config_destroy(cfg);
528                 ast_mutex_unlock(&pgsql_lock);
529                 return -1;
530         }
531
532         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
533                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
534                 tmp = "5432";
535         }
536
537         ast_free(pgdbport);
538         if (!(pgdbport = ast_strdup(tmp))) {
539                 ast_config_destroy(cfg);
540                 ast_mutex_unlock(&pgsql_lock);
541                 return -1;
542         }
543
544         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
545                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
546                 tmp = "cdr";
547         }
548
549         ast_free(table);
550         if (!(table = ast_strdup(tmp))) {
551                 ast_config_destroy(cfg);
552                 ast_mutex_unlock(&pgsql_lock);
553                 return -1;
554         }
555
556         if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
557                 ast_log(LOG_WARNING, "Encoding not specified.  Assuming LATIN9\n");
558                 tmp = "LATIN9";
559         }
560
561         ast_free(encoding);
562         if (!(encoding = ast_strdup(tmp))) {
563                 ast_config_destroy(cfg);
564                 ast_mutex_unlock(&pgsql_lock);
565                 return -1;
566         }
567
568         if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
569                 tmp = "";
570         }
571
572         ast_free(tz);
573         tz = NULL;
574
575         if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
576                 ast_config_destroy(cfg);
577                 ast_mutex_unlock(&pgsql_lock);
578                 return -1;
579         }
580
581         if (option_debug) {
582                 if (ast_strlen_zero(pghostname)) {
583                         ast_debug(1, "using default unix socket\n");
584                 } else {
585                         ast_debug(1, "got hostname of %s\n", pghostname);
586                 }
587                 ast_debug(1, "got port of %s\n", pgdbport);
588                 ast_debug(1, "got user of %s\n", pgdbuser);
589                 ast_debug(1, "got dbname of %s\n", pgdbname);
590                 ast_debug(1, "got password of %s\n", pgpassword);
591                 ast_debug(1, "got sql table name of %s\n", table);
592                 ast_debug(1, "got encoding of %s\n", encoding);
593                 ast_debug(1, "got timezone of %s\n", tz);
594         }
595
596         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
597         if (PQstatus(conn) != CONNECTION_BAD) {
598                 char sqlcmd[768];
599                 char *fname, *ftype, *flen, *fnotnull, *fdef;
600                 int i, rows, version;
601                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
602                 connected = 1;
603                 connect_time = time(NULL);
604                 records = 0;
605                 if (PQsetClientEncoding(conn, encoding)) {
606 #ifdef HAVE_PGSQL_pg_encoding_to_char
607                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
608 #else
609                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
610 #endif
611                 }
612                 version = PQserverVersion(conn);
613
614                 if (version >= 70300) {
615                         char *schemaname, *tablename;
616                         if (strchr(table, '.')) {
617                                 schemaname = ast_strdupa(table);
618                                 tablename = strchr(schemaname, '.');
619                                 *tablename++ = '\0';
620                         } else {
621                                 schemaname = "";
622                                 tablename = table;
623                         }
624
625                         /* Escape special characters in schemaname */
626                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
627                                 char *tmp = schemaname, *ptr;
628
629                                 ptr = schemaname = ast_alloca(strlen(tmp) * 2 + 1);
630                                 for (; *tmp; tmp++) {
631                                         if (strchr("\\'", *tmp)) {
632                                                 *ptr++ = *tmp;
633                                         }
634                                         *ptr++ = *tmp;
635                                 }
636                                 *ptr = '\0';
637                         }
638                         /* Escape special characters in tablename */
639                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
640                                 char *tmp = tablename, *ptr;
641
642                                 ptr = tablename = ast_alloca(strlen(tmp) * 2 + 1);
643                                 for (; *tmp; tmp++) {
644                                         if (strchr("\\'", *tmp)) {
645                                                 *ptr++ = *tmp;
646                                         }
647                                         *ptr++ = *tmp;
648                                 }
649                                 *ptr = '\0';
650                         }
651
652                         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",
653                                 tablename,
654                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
655                 } else {
656                         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);
657                 }
658                 /* Query the columns */
659                 result = PQexec(conn, sqlcmd);
660                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
661                         pgerror = PQresultErrorMessage(result);
662                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
663                         PQclear(result);
664                         unload_module();
665                         ast_mutex_unlock(&pgsql_lock);
666                         return AST_MODULE_LOAD_DECLINE;
667                 }
668
669                 rows = PQntuples(result);
670                 if (rows == 0) {
671                         ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
672                         PQclear(result);
673                         unload_module();
674                         ast_mutex_unlock(&pgsql_lock);
675                         return AST_MODULE_LOAD_DECLINE;
676                 }
677
678                 /* Clear out the columns list. */
679                 empty_columns();
680
681                 for (i = 0; i < rows; i++) {
682                         fname = PQgetvalue(result, i, 0);
683                         ftype = PQgetvalue(result, i, 1);
684                         flen = PQgetvalue(result, i, 2);
685                         fnotnull = PQgetvalue(result, i, 3);
686                         fdef = PQgetvalue(result, i, 4);
687                         if (atoi(flen) == -1) {
688                                 /* For varchar columns, the maximum length is encoded in a different field */
689                                 flen = PQgetvalue(result, i, 5);
690                         }
691                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
692                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
693                         if (cur) {
694                                 sscanf(flen, "%30d", &cur->len);
695                                 cur->name = (char *)cur + sizeof(*cur);
696                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
697                                 strcpy(cur->name, fname);
698                                 strcpy(cur->type, ftype);
699                                 if (*fnotnull == 't') {
700                                         cur->notnull = 1;
701                                 } else {
702                                         cur->notnull = 0;
703                                 }
704                                 if (!ast_strlen_zero(fdef)) {
705                                         cur->hasdefault = 1;
706                                 } else {
707                                         cur->hasdefault = 0;
708                                 }
709                                 AST_RWLIST_WRLOCK(&psql_columns);
710                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
711                                 AST_RWLIST_UNLOCK(&psql_columns);
712                         }
713                 }
714                 PQclear(result);
715         } else {
716                 pgerror = PQerrorMessage(conn);
717                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
718                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
719                 connected = 0;
720         }
721
722         ast_config_destroy(cfg);
723
724         ast_mutex_unlock(&pgsql_lock);
725         return 0;
726 }
727
728 static int load_module(void)
729 {
730         ast_cli_register_multiple(cdr_pgsql_status_cli, sizeof(cdr_pgsql_status_cli) / sizeof(struct ast_cli_entry));
731         if (config_module(0)) {
732                 return AST_MODULE_LOAD_DECLINE;
733         }
734         return ast_cdr_register(name, ast_module_info->description, pgsql_log)
735                 ? AST_MODULE_LOAD_DECLINE : 0;
736 }
737
738 static int reload(void)
739 {
740         return config_module(1);
741 }
742
743 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
744                 .load = load_module,
745                 .unload = unload_module,
746                 .reload = reload,
747                 .load_pri = AST_MODPRI_CDR_DRIVER,
748                );