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