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