res_config_pgsql: Fix a memory leak and use RAII_VAR for cleanup when practical
[asterisk/asterisk.git] / res / res_config_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999-2010, Digium, Inc.
5  *
6  * Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
7  * Mark Spencer <markster@digium.com>  - Asterisk Author
8  * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
9  *
10  * res_config_pgsql.c <PostgreSQL plugin for RealTime configuration engine>
11  *
12  * v1.0   - (07-11-05) - Initial version based on res_config_mysql v2.0
13  */
14
15 /*! \file
16  *
17  * \brief PostgreSQL plugin for Asterisk RealTime Architecture
18  *
19  * \author Mark Spencer <markster@digium.com>
20  * \author Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
21  *
22  * PostgreSQL http://www.postgresql.org
23  */
24
25 /*** MODULEINFO
26         <depend>pgsql</depend>
27         <support_level>extended</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <libpq-fe.h>                   /* PostgreSQL */
35
36 #include "asterisk/file.h"
37 #include "asterisk/channel.h"
38 #include "asterisk/pbx.h"
39 #include "asterisk/config.h"
40 #include "asterisk/module.h"
41 #include "asterisk/lock.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/cli.h"
44
45 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
46 AST_THREADSTORAGE(sql_buf);
47 AST_THREADSTORAGE(findtable_buf);
48 AST_THREADSTORAGE(where_buf);
49 AST_THREADSTORAGE(escapebuf_buf);
50 AST_THREADSTORAGE(semibuf_buf);
51
52 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
53
54 static PGconn *pgsqlConn = NULL;
55 static int version;
56 #define has_schema_support      (version > 70300 ? 1 : 0)
57
58 #define MAX_DB_OPTION_SIZE 64
59
60 struct columns {
61         char *name;
62         char *type;
63         int len;
64         unsigned int notnull:1;
65         unsigned int hasdefault:1;
66         AST_LIST_ENTRY(columns) list;
67 };
68
69 struct tables {
70         ast_rwlock_t lock;
71         AST_LIST_HEAD_NOLOCK(psql_columns, columns) columns;
72         AST_LIST_ENTRY(tables) list;
73         char name[0];
74 };
75
76 static AST_LIST_HEAD_STATIC(psql_tables, tables);
77
78 static char dbhost[MAX_DB_OPTION_SIZE] = "";
79 static char dbuser[MAX_DB_OPTION_SIZE] = "";
80 static char dbpass[MAX_DB_OPTION_SIZE] = "";
81 static char dbname[MAX_DB_OPTION_SIZE] = "";
82 static char dbsock[MAX_DB_OPTION_SIZE] = "";
83 static int dbport = 5432;
84 static time_t connect_time = 0;
85
86 static int parse_config(int reload);
87 static int pgsql_reconnect(const char *database);
88 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
89 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
90
91 static enum { RQ_WARN, RQ_CREATECLOSE, RQ_CREATECHAR } requirements;
92
93 static struct ast_cli_entry cli_realtime[] = {
94         AST_CLI_DEFINE(handle_cli_realtime_pgsql_status, "Shows connection information for the PostgreSQL RealTime driver"),
95         AST_CLI_DEFINE(handle_cli_realtime_pgsql_cache, "Shows cached tables within the PostgreSQL realtime driver"),
96 };
97
98 #define ESCAPE_STRING(buffer, stringname) \
99         do { \
100                 int len = strlen(stringname); \
101                 struct ast_str *semi = ast_str_thread_get(&semibuf_buf, len * 3 + 1); \
102                 const char *chunk = stringname; \
103                 ast_str_reset(semi); \
104                 for (; *chunk; chunk++) { \
105                         if (strchr(";^", *chunk)) { \
106                                 ast_str_append(&semi, 0, "^%02hhX", *chunk); \
107                         } else { \
108                                 ast_str_append(&semi, 0, "%c", *chunk); \
109                         } \
110                 } \
111                 if (ast_str_strlen(semi) > (ast_str_size(buffer) - 1) / 2) { \
112                         ast_str_make_space(&buffer, ast_str_strlen(semi) * 2 + 1); \
113                 } \
114                 PQescapeStringConn(pgsqlConn, ast_str_buffer(buffer), ast_str_buffer(semi), ast_str_size(buffer), &pgresult); \
115         } while (0)
116
117 static void destroy_table(struct tables *table)
118 {
119         struct columns *column;
120         ast_rwlock_wrlock(&table->lock);
121         while ((column = AST_LIST_REMOVE_HEAD(&table->columns, list))) {
122                 ast_free(column);
123         }
124         ast_rwlock_unlock(&table->lock);
125         ast_rwlock_destroy(&table->lock);
126         ast_free(table);
127 }
128
129 /*! \brief Helper function for pgsql_exec.  For running querys, use pgsql_exec()
130  *
131  *  Connect if not currently connected.  Run the given query.
132  *
133  *  \param database   database name we are connected to (used for error logging)
134  *  \param tablename  table  name we are connected to (used for error logging)
135  *  \param sql        sql query string to execute
136  *  \param result     pointer for where to store the result handle
137  *
138  *  \return -1 on fatal query error
139  *  \return -2 on query failure that resulted in disconnection
140  *  \return 0 on success
141  *
142  *  \note see pgsql_exec for full example
143  */
144 static int _pgsql_exec(const char *database, const char *tablename, const char *sql, PGresult **result)
145 {
146         ExecStatusType result_status;
147
148         if (!pgsqlConn) {
149                 ast_debug(1, "PostgreSQL connection not defined, connecting\n");
150
151                 if (pgsql_reconnect(database) != 1) {
152                         ast_log(LOG_NOTICE, "reconnect failed\n");
153                         *result = NULL;
154                         return -1;
155                 }
156
157                 ast_debug(1, "PostgreSQL connection successful\n");
158         }
159
160         *result = PQexec(pgsqlConn, sql);
161         result_status = PQresultStatus(*result);
162         if (result_status != PGRES_COMMAND_OK
163                 && result_status != PGRES_TUPLES_OK
164                 && result_status != PGRES_NONFATAL_ERROR) {
165
166                 ast_log(LOG_ERROR, "PostgreSQL RealTime: Failed to query '%s@%s'.\n", tablename, database);
167                 ast_log(LOG_ERROR, "PostgreSQL RealTime: Query Failed: %s\n", sql);
168                 ast_log(LOG_ERROR, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
169                         PQresultErrorMessage(*result),
170                         PQresStatus(result_status));
171
172                 /* we may have tried to run a command on a disconnected/disconnecting handle */
173                 /* are we no longer connected to the database... if not try again */
174                 if (PQstatus(pgsqlConn) != CONNECTION_OK) {
175                         PQfinish(pgsqlConn);
176                         pgsqlConn = NULL;
177                         return -2;
178                 }
179
180                 /* connection still okay, which means the query is just plain bad */
181                 return -1;
182         }
183
184         ast_debug(1, "PostgreSQL query successful: %s\n", sql);
185         return 0;
186 }
187
188 /*! \brief Do a postgres query, with reconnection support
189  *
190  *  Connect if not currently connected.  Run the given query
191  *  and if we're disconnected afterwards, reconnect and query again.
192  *
193  *  \param database   database name we are connected to (used for error logging)
194  *  \param tablename  table  name we are connected to (used for error logging)
195  *  \param sql        sql query string to execute
196  *  \param result     pointer for where to store the result handle
197  *
198  *  \return -1 on query failure
199  *  \return 0 on success
200  *
201  *  \code
202  *      int i, rows;
203  *      PGresult *result;
204  *      char *field_name, *field_type, *field_len, *field_notnull, *field_default;
205  *
206  *      pgsql_exec("db", "table", "SELECT 1", &result)
207  *
208  *      rows = PQntuples(result);
209  *      for (i = 0; i < rows; i++) {
210  *              field_name    = PQgetvalue(result, i, 0);
211  *              field_type    = PQgetvalue(result, i, 1);
212  *              field_len     = PQgetvalue(result, i, 2);
213  *              field_notnull = PQgetvalue(result, i, 3);
214  *              field_default = PQgetvalue(result, i, 4);
215  *      }
216  *  \endcode
217  */
218 static int pgsql_exec(const char *database, const char *tablename, const char *sql, PGresult **result)
219 {
220         int attempts = 0;
221         int res;
222
223         /* Try the query, note failure if any */
224         /* On first failure, reconnect and try again (_pgsql_exec handles reconnect) */
225         /* On second failure, treat as fatal query error */
226
227         while (attempts++ < 2) {
228                 ast_debug(1, "PostgreSQL query attempt %d\n", attempts);
229                 res = _pgsql_exec(database, tablename, sql, result);
230
231                 if (res == 0) {
232                         if (attempts > 1) {
233                                 ast_log(LOG_NOTICE, "PostgreSQL RealTime: Query finally succeeded: %s\n", sql);
234                         }
235
236                         return 0;
237                 }
238
239                 if (res == -1) {
240                         return -1; /* Still connected to db, but could not process query (fatal error) */
241                 }
242
243                 /* res == -2 (query on a disconnected handle) */
244                 ast_debug(1, "PostgreSQL query attempt %d failed, trying again\n", attempts);
245         }
246
247         return -1;
248 }
249
250 static struct tables *find_table(const char *database, const char *orig_tablename)
251 {
252         struct columns *column;
253         struct tables *table;
254         struct ast_str *sql = ast_str_thread_get(&findtable_buf, 330);
255         RAII_VAR(PGresult *, result, NULL, PQclear);
256         int exec_result;
257         char *fname, *ftype, *flen, *fnotnull, *fdef;
258         int i, rows;
259
260         AST_LIST_LOCK(&psql_tables);
261         AST_LIST_TRAVERSE(&psql_tables, table, list) {
262                 if (!strcasecmp(table->name, orig_tablename)) {
263                         ast_debug(1, "Found table in cache; now locking\n");
264                         ast_rwlock_rdlock(&table->lock);
265                         ast_debug(1, "Lock cached table; now returning\n");
266                         AST_LIST_UNLOCK(&psql_tables);
267                         return table;
268                 }
269         }
270
271         if (database == NULL) {
272                 return NULL;
273         }
274
275         ast_debug(1, "Table '%s' not found in cache, querying now\n", orig_tablename);
276
277         /* Not found, scan the table */
278         if (has_schema_support) {
279                 char *schemaname, *tablename;
280                 if (strchr(orig_tablename, '.')) {
281                         schemaname = ast_strdupa(orig_tablename);
282                         tablename = strchr(schemaname, '.');
283                         *tablename++ = '\0';
284                 } else {
285                         schemaname = "";
286                         tablename = ast_strdupa(orig_tablename);
287                 }
288
289                 /* Escape special characters in schemaname */
290                 if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
291                         char *tmp = schemaname, *ptr;
292
293                         ptr = schemaname = ast_alloca(strlen(tmp) * 2 + 1);
294                         for (; *tmp; tmp++) {
295                                 if (strchr("\\'", *tmp)) {
296                                         *ptr++ = *tmp;
297                                 }
298                                 *ptr++ = *tmp;
299                         }
300                         *ptr = '\0';
301                 }
302                 /* Escape special characters in tablename */
303                 if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
304                         char *tmp = tablename, *ptr;
305
306                         ptr = tablename = ast_alloca(strlen(tmp) * 2 + 1);
307                         for (; *tmp; tmp++) {
308                                 if (strchr("\\'", *tmp)) {
309                                         *ptr++ = *tmp;
310                                 }
311                                 *ptr++ = *tmp;
312                         }
313                         *ptr = '\0';
314                 }
315
316                 ast_str_set(&sql, 0, "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",
317                         tablename,
318                         ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
319         } else {
320                 /* Escape special characters in tablename */
321                 if (strchr(orig_tablename, '\\') || strchr(orig_tablename, '\'')) {
322                         const char *tmp = orig_tablename;
323                         char *ptr;
324
325                         orig_tablename = ptr = ast_alloca(strlen(tmp) * 2 + 1);
326                         for (; *tmp; tmp++) {
327                                 if (strchr("\\'", *tmp)) {
328                                         *ptr++ = *tmp;
329                                 }
330                                 *ptr++ = *tmp;
331                         }
332                         *ptr = '\0';
333                 }
334
335                 ast_str_set(&sql, 0, "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", orig_tablename);
336         }
337
338         exec_result = pgsql_exec(database, orig_tablename, ast_str_buffer(sql), &result);
339         ast_debug(1, "Query of table structure complete.  Now retrieving results.\n");
340         if (exec_result != 0) {
341                 ast_log(LOG_ERROR, "Failed to query database columns for table %s\n", orig_tablename);
342                 AST_LIST_UNLOCK(&psql_tables);
343                 return NULL;
344         }
345
346         if (!(table = ast_calloc(1, sizeof(*table) + strlen(orig_tablename) + 1))) {
347                 ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
348                 AST_LIST_UNLOCK(&psql_tables);
349                 return NULL;
350         }
351         strcpy(table->name, orig_tablename); /* SAFE */
352         ast_rwlock_init(&table->lock);
353         AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
354
355         rows = PQntuples(result);
356         for (i = 0; i < rows; i++) {
357                 fname = PQgetvalue(result, i, 0);
358                 ftype = PQgetvalue(result, i, 1);
359                 flen = PQgetvalue(result, i, 2);
360                 fnotnull = PQgetvalue(result, i, 3);
361                 fdef = PQgetvalue(result, i, 4);
362                 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
363
364                 if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + 2))) {
365                         ast_log(LOG_ERROR, "Unable to allocate column element for %s, %s\n", orig_tablename, fname);
366                         destroy_table(table);
367                         AST_LIST_UNLOCK(&psql_tables);
368                         return NULL;
369                 }
370
371                 if (strcmp(flen, "-1") == 0) {
372                         /* Some types, like chars, have the length stored in a different field */
373                         flen = PQgetvalue(result, i, 5);
374                         sscanf(flen, "%30d", &column->len);
375                         column->len -= 4;
376                 } else {
377                         sscanf(flen, "%30d", &column->len);
378                 }
379                 column->name = (char *)column + sizeof(*column);
380                 column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
381                 strcpy(column->name, fname);
382                 strcpy(column->type, ftype);
383                 if (*fnotnull == 't') {
384                         column->notnull = 1;
385                 } else {
386                         column->notnull = 0;
387                 }
388                 if (!ast_strlen_zero(fdef)) {
389                         column->hasdefault = 1;
390                 } else {
391                         column->hasdefault = 0;
392                 }
393                 AST_LIST_INSERT_TAIL(&table->columns, column, list);
394         }
395
396         AST_LIST_INSERT_TAIL(&psql_tables, table, list);
397         ast_rwlock_rdlock(&table->lock);
398         AST_LIST_UNLOCK(&psql_tables);
399         return table;
400 }
401
402 #define release_table(table) ast_rwlock_unlock(&(table)->lock);
403
404 static struct columns *find_column(struct tables *t, const char *colname)
405 {
406         struct columns *column;
407
408         /* Check that the column exists in the table */
409         AST_LIST_TRAVERSE(&t->columns, column, list) {
410                 if (strcmp(column->name, colname) == 0) {
411                         return column;
412                 }
413         }
414         return NULL;
415 }
416
417 static struct ast_variable *realtime_pgsql(const char *database, const char *tablename, const struct ast_variable *fields)
418 {
419         RAII_VAR(PGresult *, result, NULL, PQclear);
420         int num_rows = 0, pgresult;
421         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
422         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
423         char *stringp;
424         char *chunk;
425         char *op;
426         const struct ast_variable *field = fields;
427         struct ast_variable *var = NULL, *prev = NULL;
428
429         /*
430          * Ignore database from the extconfig.conf since it was
431          * configured by res_pgsql.conf.
432          */
433         database = dbname;
434
435         if (!tablename) {
436                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
437                 return NULL;
438         }
439
440         /* Get the first parameter and first value in our list of passed paramater/value pairs */
441         if (!field) {
442                 ast_log(LOG_WARNING,
443                                 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
444                 if (pgsqlConn) {
445                         PQfinish(pgsqlConn);
446                         pgsqlConn = NULL;
447                 }
448                 return NULL;
449         }
450
451         /* Create the first part of the query using the first parameter/value pairs we just extracted
452            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
453         op = strchr(field->name, ' ') ? "" : " =";
454
455         ESCAPE_STRING(escapebuf, field->value);
456         if (pgresult) {
457                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
458                 return NULL;
459         }
460
461         ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", tablename, field->name, op, ast_str_buffer(escapebuf));
462         while ((field = field->next)) {
463                 if (!strchr(field->name, ' '))
464                         op = " =";
465                 else
466                         op = "";
467
468                 ESCAPE_STRING(escapebuf, field->value);
469                 if (pgresult) {
470                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
471                         return NULL;
472                 }
473
474                 ast_str_append(&sql, 0, " AND %s%s '%s'", field->name, op, ast_str_buffer(escapebuf));
475         }
476
477         /* We now have our complete statement; Lets connect to the server and execute it. */
478         ast_mutex_lock(&pgsql_lock);
479
480         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
481                 ast_mutex_unlock(&pgsql_lock);
482                 return NULL;
483         }
484
485         ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
486
487         if ((num_rows = PQntuples(result)) > 0) {
488                 int i = 0;
489                 int rowIndex = 0;
490                 int numFields = PQnfields(result);
491                 char **fieldnames = NULL;
492
493                 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
494
495                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
496                         ast_mutex_unlock(&pgsql_lock);
497                         return NULL;
498                 }
499                 for (i = 0; i < numFields; i++)
500                         fieldnames[i] = PQfname(result, i);
501                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
502                         for (i = 0; i < numFields; i++) {
503                                 stringp = PQgetvalue(result, rowIndex, i);
504                                 while (stringp) {
505                                         chunk = strsep(&stringp, ";");
506                                         if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
507                                                 if (prev) {
508                                                         prev->next = ast_variable_new(fieldnames[i], chunk, "");
509                                                         if (prev->next) {
510                                                                 prev = prev->next;
511                                                         }
512                                                 } else {
513                                                         prev = var = ast_variable_new(fieldnames[i], chunk, "");
514                                                 }
515                                         }
516                                 }
517                         }
518                 }
519                 ast_free(fieldnames);
520         } else {
521                 ast_debug(1, "Postgresql RealTime: Could not find any rows in table %s@%s.\n", tablename, database);
522         }
523
524         ast_mutex_unlock(&pgsql_lock);
525
526         return var;
527 }
528
529 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, const struct ast_variable *fields)
530 {
531         RAII_VAR(PGresult *, result, NULL, PQclear);
532         int num_rows = 0, pgresult;
533         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
534         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
535         const struct ast_variable *field = fields;
536         const char *initfield = NULL;
537         char *stringp;
538         char *chunk;
539         char *op;
540         struct ast_variable *var = NULL;
541         struct ast_config *cfg = NULL;
542         struct ast_category *cat = NULL;
543
544         /*
545          * Ignore database from the extconfig.conf since it was
546          * configured by res_pgsql.conf.
547          */
548         database = dbname;
549
550         if (!table) {
551                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
552                 return NULL;
553         }
554
555         if (!(cfg = ast_config_new()))
556                 return NULL;
557
558         /* Get the first parameter and first value in our list of passed paramater/value pairs */
559         if (!field) {
560                 ast_log(LOG_WARNING,
561                                 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
562                 if (pgsqlConn) {
563                         PQfinish(pgsqlConn);
564                         pgsqlConn = NULL;
565                 }
566                 ast_config_destroy(cfg);
567                 return NULL;
568         }
569
570         initfield = ast_strdupa(field->name);
571         if ((op = strchr(initfield, ' '))) {
572                 *op = '\0';
573         }
574
575         /* Create the first part of the query using the first parameter/value pairs we just extracted
576            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
577
578         if (!strchr(field->name, ' '))
579                 op = " =";
580         else
581                 op = "";
582
583         ESCAPE_STRING(escapebuf, field->value);
584         if (pgresult) {
585                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
586                 ast_config_destroy(cfg);
587                 return NULL;
588         }
589
590         ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, field->name, op, ast_str_buffer(escapebuf));
591         while ((field = field->next)) {
592                 if (!strchr(field->name, ' '))
593                         op = " =";
594                 else
595                         op = "";
596
597                 ESCAPE_STRING(escapebuf, field->value);
598                 if (pgresult) {
599                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
600                         ast_config_destroy(cfg);
601                         return NULL;
602                 }
603
604                 ast_str_append(&sql, 0, " AND %s%s '%s'", field->name, op, ast_str_buffer(escapebuf));
605         }
606
607         if (initfield) {
608                 ast_str_append(&sql, 0, " ORDER BY %s", initfield);
609         }
610
611
612         /* We now have our complete statement; Lets connect to the server and execute it. */
613         ast_mutex_lock(&pgsql_lock);
614
615         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
616                 ast_mutex_unlock(&pgsql_lock);
617                 ast_config_destroy(cfg);
618                 return NULL;
619         } else {
620                 ExecStatusType result_status = PQresultStatus(result);
621                 if (result_status != PGRES_COMMAND_OK
622                         && result_status != PGRES_TUPLES_OK
623                         && result_status != PGRES_NONFATAL_ERROR) {
624                         ast_log(LOG_WARNING,
625                                         "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
626                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
627                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
628                                                 PQresultErrorMessage(result), PQresStatus(result_status));
629                         ast_mutex_unlock(&pgsql_lock);
630                         ast_config_destroy(cfg);
631                         return NULL;
632                 }
633         }
634
635         ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
636
637         if ((num_rows = PQntuples(result)) > 0) {
638                 int numFields = PQnfields(result);
639                 int i = 0;
640                 int rowIndex = 0;
641                 char **fieldnames = NULL;
642
643                 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
644
645                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
646                         ast_mutex_unlock(&pgsql_lock);
647                         ast_config_destroy(cfg);
648                         return NULL;
649                 }
650                 for (i = 0; i < numFields; i++)
651                         fieldnames[i] = PQfname(result, i);
652
653                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
654                         var = NULL;
655                         if (!(cat = ast_category_new("","",99999)))
656                                 continue;
657                         for (i = 0; i < numFields; i++) {
658                                 stringp = PQgetvalue(result, rowIndex, i);
659                                 while (stringp) {
660                                         chunk = strsep(&stringp, ";");
661                                         if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
662                                                 if (initfield && !strcmp(initfield, fieldnames[i])) {
663                                                         ast_category_rename(cat, chunk);
664                                                 }
665                                                 var = ast_variable_new(fieldnames[i], chunk, "");
666                                                 ast_variable_append(cat, var);
667                                         }
668                                 }
669                         }
670                         ast_category_append(cfg, cat);
671                 }
672                 ast_free(fieldnames);
673         } else {
674                 ast_debug(1, "PostgreSQL RealTime: Could not find any rows in table %s.\n", table);
675         }
676
677         ast_mutex_unlock(&pgsql_lock);
678
679         return cfg;
680 }
681
682 static int update_pgsql(const char *database, const char *tablename, const char *keyfield,
683                                                 const char *lookup, const struct ast_variable *fields)
684 {
685         RAII_VAR(PGresult *, result, NULL, PQclear);
686         int numrows = 0, pgresult;
687         const struct ast_variable *field = fields;
688         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
689         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
690         struct tables *table;
691         struct columns *column = NULL;
692
693         /*
694          * Ignore database from the extconfig.conf since it was
695          * configured by res_pgsql.conf.
696          */
697         database = dbname;
698
699         if (!tablename) {
700                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
701                 return -1;
702         }
703
704         if (!(table = find_table(database, tablename))) {
705                 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
706                 return -1;
707         }
708
709         /* Get the first parameter and first value in our list of passed paramater/value pairs */
710         if (!field) {
711                 ast_log(LOG_WARNING,
712                                 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
713                 if (pgsqlConn) {
714                         PQfinish(pgsqlConn);
715                         pgsqlConn = NULL;
716                 }
717                 release_table(table);
718                 return -1;
719         }
720
721         /* Check that the column exists in the table */
722         AST_LIST_TRAVERSE(&table->columns, column, list) {
723                 if (strcmp(column->name, field->name) == 0) {
724                         break;
725                 }
726         }
727
728         if (!column) {
729                 ast_log(LOG_ERROR, "PostgreSQL RealTime: Updating on column '%s', but that column does not exist within the table '%s'!\n", field->name, tablename);
730                 release_table(table);
731                 return -1;
732         }
733
734         /* Create the first part of the query using the first parameter/value pairs we just extracted
735            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
736
737         ESCAPE_STRING(escapebuf, field->value);
738         if (pgresult) {
739                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
740                 release_table(table);
741                 return -1;
742         }
743         ast_str_set(&sql, 0, "UPDATE %s SET %s = '%s'", tablename, field->name, ast_str_buffer(escapebuf));
744
745         while ((field = field->next)) {
746                 if (!find_column(table, field->name)) {
747                         ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s', but column does not exist!\n", field->name, tablename);
748                         continue;
749                 }
750
751                 ESCAPE_STRING(escapebuf, field->value);
752                 if (pgresult) {
753                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
754                         release_table(table);
755                         return -1;
756                 }
757
758                 ast_str_append(&sql, 0, ", %s = '%s'", field->name, ast_str_buffer(escapebuf));
759         }
760         release_table(table);
761
762         ESCAPE_STRING(escapebuf, lookup);
763         if (pgresult) {
764                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", lookup);
765                 return -1;
766         }
767
768         ast_str_append(&sql, 0, " WHERE %s = '%s'", keyfield, ast_str_buffer(escapebuf));
769
770         ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
771
772         /* We now have our complete statement; Lets connect to the server and execute it. */
773         ast_mutex_lock(&pgsql_lock);
774
775         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
776                 ast_mutex_unlock(&pgsql_lock);
777                 return -1;
778         } else {
779                 ExecStatusType result_status = PQresultStatus(result);
780                 if (result_status != PGRES_COMMAND_OK
781                         && result_status != PGRES_TUPLES_OK
782                         && result_status != PGRES_NONFATAL_ERROR) {
783                         ast_log(LOG_WARNING,
784                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
785                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
786                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
787                                                 PQresultErrorMessage(result), PQresStatus(result_status));
788                         ast_mutex_unlock(&pgsql_lock);
789                         return -1;
790                 }
791         }
792
793         numrows = atoi(PQcmdTuples(result));
794         ast_mutex_unlock(&pgsql_lock);
795
796         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
797
798         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
799          * An integer greater than zero indicates the number of rows affected
800          * Zero indicates that no records were updated
801          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
802          */
803
804         if (numrows >= 0)
805                 return (int) numrows;
806
807         return -1;
808 }
809
810 static int update2_pgsql(const char *database, const char *tablename, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
811 {
812         RAII_VAR(PGresult *, result, NULL, PQclear);
813         int numrows = 0, pgresult, first = 1;
814         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
815         const struct ast_variable *field;
816         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
817         struct ast_str *where = ast_str_thread_get(&where_buf, 100);
818         struct tables *table;
819
820         /*
821          * Ignore database from the extconfig.conf since it was
822          * configured by res_pgsql.conf.
823          */
824         database = dbname;
825
826         if (!tablename) {
827                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
828                 return -1;
829         }
830
831         if (!escapebuf || !sql || !where) {
832                 /* Memory error, already handled */
833                 return -1;
834         }
835
836         if (!(table = find_table(database, tablename))) {
837                 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
838                 return -1;
839         }
840
841         ast_str_set(&sql, 0, "UPDATE %s SET ", tablename);
842         ast_str_set(&where, 0, "WHERE");
843
844         for (field = lookup_fields; field; field = field->next) {
845                 if (!find_column(table, field->name)) {
846                         ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", field->name, tablename, database);
847                         release_table(table);
848                         return -1;
849                 }
850
851                 ESCAPE_STRING(escapebuf, field->value);
852                 if (pgresult) {
853                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
854                         release_table(table);
855                         ast_free(sql);
856                         return -1;
857                 }
858                 ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", field->name, ast_str_buffer(escapebuf));
859                 first = 0;
860         }
861
862         if (first) {
863                 ast_log(LOG_WARNING,
864                                 "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
865                 if (pgsqlConn) {
866                         PQfinish(pgsqlConn);
867                         pgsqlConn = NULL;
868                 }
869                 release_table(table);
870                 return -1;
871         }
872
873         /* Now retrieve the columns to update */
874         first = 1;
875         for (field = update_fields; field; field = field->next) {
876                 /* If the column is not within the table, then skip it */
877                 if (!find_column(table, field->name)) {
878                         ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", field->name, tablename, database);
879                         continue;
880                 }
881
882                 ESCAPE_STRING(escapebuf, field->value);
883                 if (pgresult) {
884                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
885                         release_table(table);
886                         ast_free(sql);
887                         return -1;
888                 }
889
890                 ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", field->name, ast_str_buffer(escapebuf));
891         }
892         release_table(table);
893
894         ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
895
896         ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
897
898         /* We now have our complete statement; connect to the server and execute it. */
899         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
900                 ast_mutex_unlock(&pgsql_lock);
901                 return -1;
902         }
903
904         numrows = atoi(PQcmdTuples(result));
905         ast_mutex_unlock(&pgsql_lock);
906
907         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
908
909         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
910          * An integer greater than zero indicates the number of rows affected
911          * Zero indicates that no records were updated
912          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
913          */
914
915         if (numrows >= 0) {
916                 return (int) numrows;
917         }
918
919         return -1;
920 }
921
922 static int store_pgsql(const char *database, const char *table, const struct ast_variable *fields)
923 {
924         RAII_VAR(PGresult *, result, NULL, PQclear);
925         Oid insertid;
926         struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
927         struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
928         struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
929         int pgresult;
930         const struct ast_variable *field = fields;
931
932         /*
933          * Ignore database from the extconfig.conf since it was
934          * configured by res_pgsql.conf.
935          */
936         database = dbname;
937
938         if (!table) {
939                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
940                 return -1;
941         }
942
943         /* Get the first parameter and first value in our list of passed paramater/value pairs */
944         if (!field) {
945                 ast_log(LOG_WARNING,
946                                 "PostgreSQL RealTime: Realtime storage requires at least 1 parameter and 1 value to store.\n");
947                 if (pgsqlConn) {
948                         PQfinish(pgsqlConn);
949                         pgsqlConn = NULL;
950                 }
951                 return -1;
952         }
953
954         /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
955         ast_mutex_lock(&pgsql_lock);
956         if (!pgsql_reconnect(database)) {
957                 ast_mutex_unlock(&pgsql_lock);
958                 return -1;
959         }
960
961         /* Create the first part of the query using the first parameter/value pairs we just extracted
962            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
963         ESCAPE_STRING(buf, field->name);
964         ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
965         ESCAPE_STRING(buf, field->value);
966         ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
967         while ((field = field->next)) {
968                 ESCAPE_STRING(buf, field->name);
969                 ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
970                 ESCAPE_STRING(buf, field->value);
971                 ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
972         }
973         ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
974
975         ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
976
977         if (pgsql_exec(database, table, ast_str_buffer(sql1), &result) != 0) {
978                 ast_mutex_unlock(&pgsql_lock);
979                 return -1;
980         }
981
982         insertid = PQoidValue(result);
983         ast_mutex_unlock(&pgsql_lock);
984
985         ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s, id: %u\n", table, insertid);
986
987         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
988          * An integer greater than zero indicates the number of rows affected
989          * Zero indicates that no records were updated
990          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
991          */
992
993         if (insertid >= 0)
994                 return (int) insertid;
995
996         return -1;
997 }
998
999 static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, const struct ast_variable *fields)
1000 {
1001         RAII_VAR(PGresult *, result, NULL, PQclear);
1002         int numrows = 0;
1003         int pgresult;
1004         struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
1005         struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
1006         const struct ast_variable *field;
1007
1008         /*
1009          * Ignore database from the extconfig.conf since it was
1010          * configured by res_pgsql.conf.
1011          */
1012         database = dbname;
1013
1014         if (!table) {
1015                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
1016                 return -1;
1017         }
1018
1019         /* Get the first parameter and first value in our list of passed paramater/value pairs */
1020         /*newparam = va_arg(ap, const char *);
1021         newval = va_arg(ap, const char *);
1022         if (!newparam || !newval) {*/
1023         if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup))  {
1024                 ast_log(LOG_WARNING,
1025                                 "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
1026                 if (pgsqlConn) {
1027                         PQfinish(pgsqlConn);
1028                         pgsqlConn = NULL;
1029                 };
1030                 return -1;
1031         }
1032
1033         /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
1034         ast_mutex_lock(&pgsql_lock);
1035         if (!pgsql_reconnect(database)) {
1036                 ast_mutex_unlock(&pgsql_lock);
1037                 return -1;
1038         }
1039
1040
1041         /* Create the first part of the query using the first parameter/value pairs we just extracted
1042            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
1043
1044         ESCAPE_STRING(buf1, keyfield);
1045         ESCAPE_STRING(buf2, lookup);
1046         ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
1047         for (field = fields; field; field = field->next) {
1048                 ESCAPE_STRING(buf1, field->name);
1049                 ESCAPE_STRING(buf2, field->value);
1050                 ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
1051         }
1052
1053         ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
1054
1055         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
1056                 ast_mutex_unlock(&pgsql_lock);
1057                 return -1;
1058         }
1059
1060         numrows = atoi(PQcmdTuples(result));
1061         ast_mutex_unlock(&pgsql_lock);
1062
1063         ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
1064
1065         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
1066          * An integer greater than zero indicates the number of rows affected
1067          * Zero indicates that no records were updated
1068          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
1069          */
1070
1071         if (numrows >= 0)
1072                 return (int) numrows;
1073
1074         return -1;
1075 }
1076
1077
1078 static struct ast_config *config_pgsql(const char *database, const char *table,
1079                                                                            const char *file, struct ast_config *cfg,
1080                                                                            struct ast_flags flags, const char *suggested_incl, const char *who_asked)
1081 {
1082         RAII_VAR(PGresult *, result, NULL, PQclear);
1083         long num_rows;
1084         struct ast_variable *new_v;
1085         struct ast_category *cur_cat = NULL;
1086         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
1087         char last[80];
1088         int last_cat_metric = 0;
1089
1090         last[0] = '\0';
1091
1092         /*
1093          * Ignore database from the extconfig.conf since it is
1094          * configured by res_pgsql.conf.
1095          */
1096         database = dbname;
1097
1098         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
1099                 ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
1100                 return NULL;
1101         }
1102
1103         ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
1104                         "WHERE filename='%s' and commented=0 "
1105                         "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
1106
1107         ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
1108
1109         ast_mutex_lock(&pgsql_lock);
1110
1111         /* We now have our complete statement; Lets connect to the server and execute it. */
1112         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
1113                 ast_mutex_unlock(&pgsql_lock);
1114                 return NULL;
1115         }
1116
1117         if ((num_rows = PQntuples(result)) > 0) {
1118                 int rowIndex = 0;
1119
1120                 ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
1121
1122                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
1123                         char *field_category = PQgetvalue(result, rowIndex, 0);
1124                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
1125                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
1126                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
1127                         if (!strcmp(field_var_name, "#include")) {
1128                                 if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
1129                                         ast_mutex_unlock(&pgsql_lock);
1130                                         return NULL;
1131                                 }
1132                                 continue;
1133                         }
1134
1135                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
1136                                 cur_cat = ast_category_new(field_category, "", 99999);
1137                                 if (!cur_cat)
1138                                         break;
1139                                 ast_copy_string(last, field_category, sizeof(last));
1140                                 last_cat_metric = atoi(field_cat_metric);
1141                                 ast_category_append(cfg, cur_cat);
1142                         }
1143                         new_v = ast_variable_new(field_var_name, field_var_val, "");
1144                         ast_variable_append(cur_cat, new_v);
1145                 }
1146         } else {
1147                 ast_log(LOG_WARNING,
1148                                 "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
1149         }
1150
1151         ast_mutex_unlock(&pgsql_lock);
1152
1153         return cfg;
1154 }
1155
1156 static int require_pgsql(const char *database, const char *tablename, va_list ap)
1157 {
1158         struct columns *column;
1159         struct tables *table;
1160         char *elm;
1161         int type, size, res = 0;
1162
1163         /*
1164          * Ignore database from the extconfig.conf since it was
1165          * configured by res_pgsql.conf.
1166          */
1167         database = dbname;
1168
1169         table = find_table(database, tablename);
1170         if (!table) {
1171                 ast_log(LOG_WARNING, "Table %s not found in database.  This table should exist if you're using realtime.\n", tablename);
1172                 return -1;
1173         }
1174
1175         while ((elm = va_arg(ap, char *))) {
1176                 type = va_arg(ap, require_type);
1177                 size = va_arg(ap, int);
1178                 AST_LIST_TRAVERSE(&table->columns, column, list) {
1179                         if (strcmp(column->name, elm) == 0) {
1180                                 /* Char can hold anything, as long as it is large enough */
1181                                 if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
1182                                         if ((size > column->len) && column->len != -1) {
1183                                                 ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
1184                                                 res = -1;
1185                                         }
1186                                 } else if (strncmp(column->type, "int", 3) == 0) {
1187                                         int typesize = atoi(column->type + 3);
1188                                         /* Integers can hold only other integers */
1189                                         if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1190                                                 type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
1191                                                 type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
1192                                                 type == RQ_UINTEGER2) && typesize == 2) {
1193                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1194                                                 res = -1;
1195                                         } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1196                                                 type == RQ_UINTEGER4) && typesize == 4) {
1197                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1198                                                 res = -1;
1199                                         } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
1200                                                 ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
1201                                                         column->name,
1202                                                                 type == RQ_CHAR ? "char" :
1203                                                                 type == RQ_DATETIME ? "datetime" :
1204                                                                 type == RQ_DATE ? "date" :
1205                                                                 type == RQ_FLOAT ? "float" :
1206                                                                 "a rather stiff drink ",
1207                                                         size, column->type);
1208                                                 res = -1;
1209                                         }
1210                                 } else if (strncmp(column->type, "float", 5) == 0) {
1211                                         if (!ast_rq_is_int(type) && type != RQ_FLOAT) {
1212                                                 ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1213                                                 res = -1;
1214                                         }
1215                                 } else if (strncmp(column->type, "timestamp", 9) == 0) {
1216                                         if (type != RQ_DATETIME && type != RQ_DATE) {
1217                                                 ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1218                                                 res = -1;
1219                                         }
1220                                 } else { /* There are other types that no module implements yet */
1221                                         ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
1222                                         res = -1;
1223                                 }
1224                                 break;
1225                         }
1226                 }
1227
1228                 if (!column) {
1229                         if (requirements == RQ_WARN) {
1230                                 ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
1231                         } else {
1232                                 struct ast_str *sql = ast_str_create(100);
1233                                 char fieldtype[15];
1234                                 PGresult *result;
1235
1236                                 if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
1237                                         /* Size is minimum length; make it at least 50% greater,
1238                                          * just to be sure, because PostgreSQL doesn't support
1239                                          * resizing columns. */
1240                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(%d)",
1241                                                 size < 15 ? size * 2 :
1242                                                 (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
1243                                 } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
1244                                         snprintf(fieldtype, sizeof(fieldtype), "INT2");
1245                                 } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
1246                                         snprintf(fieldtype, sizeof(fieldtype), "INT4");
1247                                 } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
1248                                         snprintf(fieldtype, sizeof(fieldtype), "INT8");
1249                                 } else if (type == RQ_UINTEGER8) {
1250                                         /* No such type on PostgreSQL */
1251                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
1252                                 } else if (type == RQ_FLOAT) {
1253                                         snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
1254                                 } else if (type == RQ_DATE) {
1255                                         snprintf(fieldtype, sizeof(fieldtype), "DATE");
1256                                 } else if (type == RQ_DATETIME) {
1257                                         snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
1258                                 } else {
1259                                         ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
1260                                         ast_free(sql);
1261                                         continue;
1262                                 }
1263                                 ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
1264                                 ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
1265
1266                                 ast_mutex_lock(&pgsql_lock);
1267                                 ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
1268
1269                                 if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
1270                                                 ast_mutex_unlock(&pgsql_lock);
1271                                         return -1;
1272                                 }
1273
1274                                 ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
1275                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1276                                         ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1277                                 }
1278                                 PQclear(result);
1279                                 ast_mutex_unlock(&pgsql_lock);
1280
1281                                 ast_free(sql);
1282                         }
1283                 }
1284         }
1285         release_table(table);
1286         return res;
1287 }
1288
1289 static int unload_pgsql(const char *database, const char *tablename)
1290 {
1291         struct tables *cur;
1292
1293         /*
1294          * Ignore database from the extconfig.conf since it was
1295          * configured by res_pgsql.conf.
1296          */
1297         database = dbname;
1298
1299         ast_debug(2, "About to lock table cache list\n");
1300         AST_LIST_LOCK(&psql_tables);
1301         ast_debug(2, "About to traverse table cache list\n");
1302         AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
1303                 if (strcmp(cur->name, tablename) == 0) {
1304                         ast_debug(2, "About to remove matching cache entry\n");
1305                         AST_LIST_REMOVE_CURRENT(list);
1306                         ast_debug(2, "About to destroy matching cache entry\n");
1307                         destroy_table(cur);
1308                         ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
1309                         break;
1310                 }
1311         }
1312         AST_LIST_TRAVERSE_SAFE_END
1313         AST_LIST_UNLOCK(&psql_tables);
1314         ast_debug(2, "About to return\n");
1315         return cur ? 0 : -1;
1316 }
1317
1318 static struct ast_config_engine pgsql_engine = {
1319         .name = "pgsql",
1320         .load_func = config_pgsql,
1321         .realtime_func = realtime_pgsql,
1322         .realtime_multi_func = realtime_multi_pgsql,
1323         .store_func = store_pgsql,
1324         .destroy_func = destroy_pgsql,
1325         .update_func = update_pgsql,
1326         .update2_func = update2_pgsql,
1327         .require_func = require_pgsql,
1328         .unload_func = unload_pgsql,
1329 };
1330
1331 static int load_module(void)
1332 {
1333         if(!parse_config(0))
1334                 return AST_MODULE_LOAD_DECLINE;
1335
1336         ast_config_engine_register(&pgsql_engine);
1337         ast_verb(1, "PostgreSQL RealTime driver loaded.\n");
1338         ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1339
1340         return 0;
1341 }
1342
1343 static int unload_module(void)
1344 {
1345         struct tables *table;
1346         /* Acquire control before doing anything to the module itself. */
1347         ast_mutex_lock(&pgsql_lock);
1348
1349         if (pgsqlConn) {
1350                 PQfinish(pgsqlConn);
1351                 pgsqlConn = NULL;
1352         }
1353         ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1354         ast_config_engine_deregister(&pgsql_engine);
1355         ast_verb(1, "PostgreSQL RealTime unloaded.\n");
1356
1357         /* Destroy cached table info */
1358         AST_LIST_LOCK(&psql_tables);
1359         while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
1360                 destroy_table(table);
1361         }
1362         AST_LIST_UNLOCK(&psql_tables);
1363
1364         /* Unlock so something else can destroy the lock. */
1365         ast_mutex_unlock(&pgsql_lock);
1366
1367         return 0;
1368 }
1369
1370 static int reload(void)
1371 {
1372         parse_config(1);
1373
1374         return 0;
1375 }
1376
1377 static int parse_config(int is_reload)
1378 {
1379         struct ast_config *config;
1380         const char *s;
1381         struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1382
1383         config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
1384         if (config == CONFIG_STATUS_FILEUNCHANGED) {
1385                 return 0;
1386         }
1387
1388         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1389                 ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
1390                 return 0;
1391         }
1392
1393         ast_mutex_lock(&pgsql_lock);
1394
1395         if (pgsqlConn) {
1396                 PQfinish(pgsqlConn);
1397                 pgsqlConn = NULL;
1398         }
1399
1400         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
1401                 ast_log(LOG_WARNING,
1402                                 "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
1403                 strcpy(dbuser, "asterisk");
1404         } else {
1405                 ast_copy_string(dbuser, s, sizeof(dbuser));
1406         }
1407
1408         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
1409                 ast_log(LOG_WARNING,
1410                                 "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
1411                 strcpy(dbpass, "asterisk");
1412         } else {
1413                 ast_copy_string(dbpass, s, sizeof(dbpass));
1414         }
1415
1416         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
1417                 ast_log(LOG_WARNING,
1418                                 "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
1419                 dbhost[0] = '\0';
1420         } else {
1421                 ast_copy_string(dbhost, s, sizeof(dbhost));
1422         }
1423
1424         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
1425                 ast_log(LOG_WARNING,
1426                                 "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
1427                 strcpy(dbname, "asterisk");
1428         } else {
1429                 ast_copy_string(dbname, s, sizeof(dbname));
1430         }
1431
1432         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
1433                 ast_log(LOG_WARNING,
1434                                 "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
1435                 dbport = 5432;
1436         } else {
1437                 dbport = atoi(s);
1438         }
1439
1440         if (!ast_strlen_zero(dbhost)) {
1441                 /* No socket needed */
1442         } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
1443                 ast_log(LOG_WARNING,
1444                                 "PostgreSQL RealTime: No database socket found, using '/tmp/.s.PGSQL.%d' as default.\n", dbport);
1445                 strcpy(dbsock, "/tmp");
1446         } else {
1447                 ast_copy_string(dbsock, s, sizeof(dbsock));
1448         }
1449
1450         if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
1451                 ast_log(LOG_WARNING,
1452                                 "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
1453                 requirements = RQ_WARN;
1454         } else if (!strcasecmp(s, "createclose")) {
1455                 requirements = RQ_CREATECLOSE;
1456         } else if (!strcasecmp(s, "createchar")) {
1457                 requirements = RQ_CREATECHAR;
1458         }
1459
1460         ast_config_destroy(config);
1461
1462         if (option_debug) {
1463                 if (!ast_strlen_zero(dbhost)) {
1464                         ast_debug(1, "PostgreSQL RealTime Host: %s\n", dbhost);
1465                         ast_debug(1, "PostgreSQL RealTime Port: %i\n", dbport);
1466                 } else {
1467                         ast_debug(1, "PostgreSQL RealTime Socket: %s\n", dbsock);
1468                 }
1469                 ast_debug(1, "PostgreSQL RealTime User: %s\n", dbuser);
1470                 ast_debug(1, "PostgreSQL RealTime Password: %s\n", dbpass);
1471                 ast_debug(1, "PostgreSQL RealTime DBName: %s\n", dbname);
1472         }
1473
1474         if (!pgsql_reconnect(NULL)) {
1475                 ast_log(LOG_WARNING,
1476                                 "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
1477                 ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
1478         }
1479
1480         ast_verb(2, "PostgreSQL RealTime reloaded.\n");
1481
1482         /* Done reloading. Release lock so others can now use driver. */
1483         ast_mutex_unlock(&pgsql_lock);
1484
1485         return 1;
1486 }
1487
1488 static int pgsql_reconnect(const char *database)
1489 {
1490         char my_database[50];
1491
1492         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
1493
1494         /* mutex lock should have been locked before calling this function. */
1495
1496         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
1497                 PQfinish(pgsqlConn);
1498                 pgsqlConn = NULL;
1499         }
1500
1501         /* DB password can legitimately be 0-length */
1502         if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
1503                 struct ast_str *connInfo = ast_str_create(128);
1504
1505                 ast_str_set(&connInfo, 0, "host=%s port=%d dbname=%s user=%s",
1506                         S_OR(dbhost, dbsock), dbport, my_database, dbuser);
1507                 if (!ast_strlen_zero(dbpass))
1508                         ast_str_append(&connInfo, 0, " password=%s", dbpass);
1509
1510                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1511                 pgsqlConn = PQconnectdb(ast_str_buffer(connInfo));
1512                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1513                 ast_free(connInfo);
1514                 connInfo = NULL;
1515
1516                 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
1517                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1518                         ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
1519                         connect_time = time(NULL);
1520                         version = PQserverVersion(pgsqlConn);
1521                         return 1;
1522                 } else {
1523                         ast_log(LOG_ERROR,
1524                                         "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
1525                                         my_database, dbhost, PQresultErrorMessage(NULL));
1526                         return 0;
1527                 }
1528         } else {
1529                 ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
1530                 return 1;
1531         }
1532 }
1533
1534 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1535 {
1536         struct tables *cur;
1537         int l, which;
1538         char *ret = NULL;
1539
1540         switch (cmd) {
1541         case CLI_INIT:
1542                 e->command = "realtime show pgsql cache";
1543                 e->usage =
1544                         "Usage: realtime show pgsql cache [<table>]\n"
1545                         "       Shows table cache for the PostgreSQL RealTime driver\n";
1546                 return NULL;
1547         case CLI_GENERATE:
1548                 if (a->argc != 4) {
1549                         return NULL;
1550                 }
1551                 l = strlen(a->word);
1552                 which = 0;
1553                 AST_LIST_LOCK(&psql_tables);
1554                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1555                         if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
1556                                 ret = ast_strdup(cur->name);
1557                                 break;
1558                         }
1559                 }
1560                 AST_LIST_UNLOCK(&psql_tables);
1561                 return ret;
1562         }
1563
1564         if (a->argc == 4) {
1565                 /* List of tables */
1566                 AST_LIST_LOCK(&psql_tables);
1567                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1568                         ast_cli(a->fd, "%s\n", cur->name);
1569                 }
1570                 AST_LIST_UNLOCK(&psql_tables);
1571         } else if (a->argc == 5) {
1572                 /* List of columns */
1573                 if ((cur = find_table(NULL, a->argv[4]))) {
1574                         struct columns *col;
1575                         ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
1576                         ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
1577                         AST_LIST_TRAVERSE(&cur->columns, col, list) {
1578                                 ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
1579                         }
1580                         release_table(cur);
1581                 } else {
1582                         ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
1583                 }
1584         }
1585         return 0;
1586 }
1587
1588 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1589 {
1590         char status[256], credentials[100] = "";
1591         int ctimesec = time(NULL) - connect_time;
1592
1593         switch (cmd) {
1594         case CLI_INIT:
1595                 e->command = "realtime show pgsql status";
1596                 e->usage =
1597                         "Usage: realtime show pgsql status\n"
1598                         "       Shows connection information for the PostgreSQL RealTime driver\n";
1599                 return NULL;
1600         case CLI_GENERATE:
1601                 return NULL;
1602         }
1603
1604         if (a->argc != 4)
1605                 return CLI_SHOWUSAGE;
1606
1607         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1608                 if (!ast_strlen_zero(dbhost))
1609                         snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
1610                 else if (!ast_strlen_zero(dbsock))
1611                         snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
1612                 else
1613                         snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
1614
1615                 if (!ast_strlen_zero(dbuser))
1616                         snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
1617
1618                 if (ctimesec > 31536000)
1619                         ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1620                                         status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
1621                                         (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1622                 else if (ctimesec > 86400)
1623                         ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
1624                                         credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
1625                                         ctimesec % 60);
1626                 else if (ctimesec > 3600)
1627                         ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
1628                                         ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1629                 else if (ctimesec > 60)
1630                         ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
1631                                         ctimesec % 60);
1632                 else
1633                         ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1634
1635                 return CLI_SUCCESS;
1636         } else {
1637                 return CLI_FAILURE;
1638         }
1639 }
1640
1641 /* needs usecount semantics defined */
1642 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL RealTime Configuration Driver",
1643                 .load = load_module,
1644                 .unload = unload_module,
1645                 .reload = reload,
1646                 .load_pri = AST_MODPRI_REALTIME_DRIVER,
1647                );