Merged revisions 328247 via svnmerge from
[asterisk/asterisk.git] / res / res_config_pgsql.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
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  * \extref 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  *  \example 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  *  \example
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  *
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         PGresult *result;
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 = 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 = 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 = 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                 PQclear(result);
343                 AST_LIST_UNLOCK(&psql_tables);
344                 return NULL;
345         }
346
347         if (!(table = ast_calloc(1, sizeof(*table) + strlen(orig_tablename) + 1))) {
348                 ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
349                 PQclear(result);
350                 AST_LIST_UNLOCK(&psql_tables);
351                 return NULL;
352         }
353         strcpy(table->name, orig_tablename); /* SAFE */
354         ast_rwlock_init(&table->lock);
355         AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
356
357         rows = PQntuples(result);
358         for (i = 0; i < rows; i++) {
359                 fname = PQgetvalue(result, i, 0);
360                 ftype = PQgetvalue(result, i, 1);
361                 flen = PQgetvalue(result, i, 2);
362                 fnotnull = PQgetvalue(result, i, 3);
363                 fdef = PQgetvalue(result, i, 4);
364                 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
365
366                 if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + 2))) {
367                         ast_log(LOG_ERROR, "Unable to allocate column element for %s, %s\n", orig_tablename, fname);
368                         PQclear(result);
369                         destroy_table(table);
370                         AST_LIST_UNLOCK(&psql_tables);
371                         return NULL;
372                 }
373
374                 if (strcmp(flen, "-1") == 0) {
375                         /* Some types, like chars, have the length stored in a different field */
376                         flen = PQgetvalue(result, i, 5);
377                         sscanf(flen, "%30d", &column->len);
378                         column->len -= 4;
379                 } else {
380                         sscanf(flen, "%30d", &column->len);
381                 }
382                 column->name = (char *)column + sizeof(*column);
383                 column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
384                 strcpy(column->name, fname);
385                 strcpy(column->type, ftype);
386                 if (*fnotnull == 't') {
387                         column->notnull = 1;
388                 } else {
389                         column->notnull = 0;
390                 }
391                 if (!ast_strlen_zero(fdef)) {
392                         column->hasdefault = 1;
393                 } else {
394                         column->hasdefault = 0;
395                 }
396                 AST_LIST_INSERT_TAIL(&table->columns, column, list);
397         }
398         PQclear(result);
399
400         AST_LIST_INSERT_TAIL(&psql_tables, table, list);
401         ast_rwlock_rdlock(&table->lock);
402         AST_LIST_UNLOCK(&psql_tables);
403         return table;
404 }
405
406 #define release_table(table) ast_rwlock_unlock(&(table)->lock);
407
408 static struct columns *find_column(struct tables *t, const char *colname)
409 {
410         struct columns *column;
411
412         /* Check that the column exists in the table */
413         AST_LIST_TRAVERSE(&t->columns, column, list) {
414                 if (strcmp(column->name, colname) == 0) {
415                         return column;
416                 }
417         }
418         return NULL;
419 }
420
421 static struct ast_variable *realtime_pgsql(const char *database, const char *tablename, va_list ap)
422 {
423         PGresult *result = NULL;
424         int num_rows = 0, pgresult;
425         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
426         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
427         char *stringp;
428         char *chunk;
429         char *op;
430         const char *newparam, *newval;
431         struct ast_variable *var = NULL, *prev = NULL;
432
433         if (!tablename) {
434                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
435                 return NULL;
436         }
437
438         /* Get the first parameter and first value in our list of passed paramater/value pairs */
439         newparam = va_arg(ap, const char *);
440         newval = va_arg(ap, const char *);
441         if (!newparam || !newval) {
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(newparam, ' ') ? "" : " =";
454
455         ESCAPE_STRING(escapebuf, newval);
456         if (pgresult) {
457                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
458                 va_end(ap);
459                 return NULL;
460         }
461
462         ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", tablename, newparam, op, ast_str_buffer(escapebuf));
463         while ((newparam = va_arg(ap, const char *))) {
464                 newval = va_arg(ap, const char *);
465                 if (!strchr(newparam, ' '))
466                         op = " =";
467                 else
468                         op = "";
469
470                 ESCAPE_STRING(escapebuf, newval);
471                 if (pgresult) {
472                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
473                         va_end(ap);
474                         return NULL;
475                 }
476
477                 ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
478         }
479         va_end(ap);
480
481         /* We now have our complete statement; Lets connect to the server and execute it. */
482         ast_mutex_lock(&pgsql_lock);
483
484         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
485                 PQclear(result);
486                 ast_mutex_unlock(&pgsql_lock);
487                 return NULL;
488         }
489
490         ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
491
492         if ((num_rows = PQntuples(result)) > 0) {
493                 int i = 0;
494                 int rowIndex = 0;
495                 int numFields = PQnfields(result);
496                 char **fieldnames = NULL;
497
498                 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
499
500                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
501                         PQclear(result);
502                         ast_mutex_unlock(&pgsql_lock);
503                         return NULL;
504                 }
505                 for (i = 0; i < numFields; i++)
506                         fieldnames[i] = PQfname(result, i);
507                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
508                         for (i = 0; i < numFields; i++) {
509                                 stringp = PQgetvalue(result, rowIndex, i);
510                                 while (stringp) {
511                                         chunk = strsep(&stringp, ";");
512                                         if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
513                                                 if (prev) {
514                                                         prev->next = ast_variable_new(fieldnames[i], chunk, "");
515                                                         if (prev->next) {
516                                                                 prev = prev->next;
517                                                         }
518                                                 } else {
519                                                         prev = var = ast_variable_new(fieldnames[i], chunk, "");
520                                                 }
521                                         }
522                                 }
523                         }
524                 }
525                 ast_free(fieldnames);
526         } else {
527                 ast_debug(1, "Postgresql RealTime: Could not find any rows in table %s@%s.\n", tablename, database);
528         }
529
530         PQclear(result);
531         ast_mutex_unlock(&pgsql_lock);
532
533         return var;
534 }
535
536 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, va_list ap)
537 {
538         PGresult *result = NULL;
539         int num_rows = 0, pgresult;
540         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
541         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
542         const char *initfield = NULL;
543         char *stringp;
544         char *chunk;
545         char *op;
546         const char *newparam, *newval;
547         struct ast_variable *var = NULL;
548         struct ast_config *cfg = NULL;
549         struct ast_category *cat = NULL;
550
551         if (!table) {
552                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
553                 return NULL;
554         }
555
556         if (!(cfg = ast_config_new()))
557                 return NULL;
558
559         /* Get the first parameter and first value in our list of passed paramater/value pairs */
560         newparam = va_arg(ap, const char *);
561         newval = va_arg(ap, const char *);
562         if (!newparam || !newval) {
563                 ast_log(LOG_WARNING,
564                                 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
565                 if (pgsqlConn) {
566                         PQfinish(pgsqlConn);
567                         pgsqlConn = NULL;
568                 }
569                 return NULL;
570         }
571
572         initfield = ast_strdupa(newparam);
573         if ((op = strchr(initfield, ' '))) {
574                 *op = '\0';
575         }
576
577         /* Create the first part of the query using the first parameter/value pairs we just extracted
578            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
579
580         if (!strchr(newparam, ' '))
581                 op = " =";
582         else
583                 op = "";
584
585         ESCAPE_STRING(escapebuf, newval);
586         if (pgresult) {
587                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
588                 va_end(ap);
589                 return NULL;
590         }
591
592         ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, ast_str_buffer(escapebuf));
593         while ((newparam = va_arg(ap, const char *))) {
594                 newval = va_arg(ap, const char *);
595                 if (!strchr(newparam, ' '))
596                         op = " =";
597                 else
598                         op = "";
599
600                 ESCAPE_STRING(escapebuf, newval);
601                 if (pgresult) {
602                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
603                         va_end(ap);
604                         return NULL;
605                 }
606
607                 ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
608         }
609
610         if (initfield) {
611                 ast_str_append(&sql, 0, " ORDER BY %s", initfield);
612         }
613
614         va_end(ap);
615
616         /* We now have our complete statement; Lets connect to the server and execute it. */
617         ast_mutex_lock(&pgsql_lock);
618
619         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
620                 ast_mutex_unlock(&pgsql_lock);
621                 return NULL;
622         } else {
623                 ExecStatusType result_status = PQresultStatus(result);
624                 if (result_status != PGRES_COMMAND_OK
625                         && result_status != PGRES_TUPLES_OK
626                         && result_status != PGRES_NONFATAL_ERROR) {
627                         ast_log(LOG_WARNING,
628                                         "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
629                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
630                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
631                                                 PQresultErrorMessage(result), PQresStatus(result_status));
632                         PQclear(result);
633                         ast_mutex_unlock(&pgsql_lock);
634                         return NULL;
635                 }
636         }
637
638         ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
639
640         if ((num_rows = PQntuples(result)) > 0) {
641                 int numFields = PQnfields(result);
642                 int i = 0;
643                 int rowIndex = 0;
644                 char **fieldnames = NULL;
645
646                 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
647
648                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
649                         PQclear(result);
650                         ast_mutex_unlock(&pgsql_lock);
651                         return NULL;
652                 }
653                 for (i = 0; i < numFields; i++)
654                         fieldnames[i] = PQfname(result, i);
655
656                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
657                         var = NULL;
658                         if (!(cat = ast_category_new("","",99999)))
659                                 continue;
660                         for (i = 0; i < numFields; i++) {
661                                 stringp = PQgetvalue(result, rowIndex, i);
662                                 while (stringp) {
663                                         chunk = strsep(&stringp, ";");
664                                         if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
665                                                 if (initfield && !strcmp(initfield, fieldnames[i])) {
666                                                         ast_category_rename(cat, chunk);
667                                                 }
668                                                 var = ast_variable_new(fieldnames[i], chunk, "");
669                                                 ast_variable_append(cat, var);
670                                         }
671                                 }
672                         }
673                         ast_category_append(cfg, cat);
674                 }
675                 ast_free(fieldnames);
676         } else {
677                 ast_debug(1, "PostgreSQL RealTime: Could not find any rows in table %s.\n", table);
678         }
679
680         PQclear(result);
681         ast_mutex_unlock(&pgsql_lock);
682
683         return cfg;
684 }
685
686 static int update_pgsql(const char *database, const char *tablename, const char *keyfield,
687                                                 const char *lookup, va_list ap)
688 {
689         PGresult *result = NULL;
690         int numrows = 0, pgresult;
691         const char *newparam, *newval;
692         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
693         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
694         struct tables *table;
695         struct columns *column = NULL;
696
697         if (!tablename) {
698                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
699                 return -1;
700         }
701
702         if (!(table = find_table(database, tablename))) {
703                 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
704                 return -1;
705         }
706
707         /* Get the first parameter and first value in our list of passed paramater/value pairs */
708         newparam = va_arg(ap, const char *);
709         newval = va_arg(ap, const char *);
710         if (!newparam || !newval) {
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, newparam) == 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", newparam, 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, newval);
738         if (pgresult) {
739                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
740                 va_end(ap);
741                 release_table(table);
742                 return -1;
743         }
744         ast_str_set(&sql, 0, "UPDATE %s SET %s = '%s'", tablename, newparam, ast_str_buffer(escapebuf));
745
746         while ((newparam = va_arg(ap, const char *))) {
747                 newval = va_arg(ap, const char *);
748
749                 if (!find_column(table, newparam)) {
750                         ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s', but column does not exist!\n", newparam, tablename);
751                         continue;
752                 }
753
754                 ESCAPE_STRING(escapebuf, newval);
755                 if (pgresult) {
756                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
757                         va_end(ap);
758                         release_table(table);
759                         return -1;
760                 }
761
762                 ast_str_append(&sql, 0, ", %s = '%s'", newparam, ast_str_buffer(escapebuf));
763         }
764         va_end(ap);
765         release_table(table);
766
767         ESCAPE_STRING(escapebuf, lookup);
768         if (pgresult) {
769                 ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", lookup);
770                 va_end(ap);
771                 return -1;
772         }
773
774         ast_str_append(&sql, 0, " WHERE %s = '%s'", keyfield, ast_str_buffer(escapebuf));
775
776         ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
777
778         /* We now have our complete statement; Lets connect to the server and execute it. */
779         ast_mutex_lock(&pgsql_lock);
780
781         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
782                 ast_mutex_unlock(&pgsql_lock);
783                 return -1;
784         } else {
785                 ExecStatusType result_status = PQresultStatus(result);
786                 if (result_status != PGRES_COMMAND_OK
787                         && result_status != PGRES_TUPLES_OK
788                         && result_status != PGRES_NONFATAL_ERROR) {
789                         ast_log(LOG_WARNING,
790                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
791                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
792                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
793                                                 PQresultErrorMessage(result), PQresStatus(result_status));
794                         PQclear(result);
795                         ast_mutex_unlock(&pgsql_lock);
796                         return -1;
797                 }
798         }
799
800         numrows = atoi(PQcmdTuples(result));
801         ast_mutex_unlock(&pgsql_lock);
802
803         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
804
805         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
806          * An integer greater than zero indicates the number of rows affected
807          * Zero indicates that no records were updated
808          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
809          */
810
811         if (numrows >= 0)
812                 return (int) numrows;
813
814         return -1;
815 }
816
817 static int update2_pgsql(const char *database, const char *tablename, va_list ap)
818 {
819         PGresult *result = NULL;
820         int numrows = 0, pgresult, first = 1;
821         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
822         const char *newparam, *newval;
823         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
824         struct ast_str *where = ast_str_thread_get(&where_buf, 100);
825         struct tables *table;
826
827         if (!tablename) {
828                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
829                 return -1;
830         }
831
832         if (!escapebuf || !sql || !where) {
833                 /* Memory error, already handled */
834                 return -1;
835         }
836
837         if (!(table = find_table(database, tablename))) {
838                 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
839                 return -1;
840         }
841
842         ast_str_set(&sql, 0, "UPDATE %s SET ", tablename);
843         ast_str_set(&where, 0, "WHERE");
844
845         while ((newparam = va_arg(ap, const char *))) {
846                 if (!find_column(table, newparam)) {
847                         ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", newparam, tablename, database);
848                         release_table(table);
849                         return -1;
850                 }
851
852                 newval = va_arg(ap, const char *);
853                 ESCAPE_STRING(escapebuf, newval);
854                 if (pgresult) {
855                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
856                         release_table(table);
857                         ast_free(sql);
858                         return -1;
859                 }
860                 ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", newparam, ast_str_buffer(escapebuf));
861                 first = 0;
862         }
863
864         if (first) {
865                 ast_log(LOG_WARNING,
866                                 "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
867                 if (pgsqlConn) {
868                         PQfinish(pgsqlConn);
869                         pgsqlConn = NULL;
870                 }
871                 release_table(table);
872                 return -1;
873         }
874
875         /* Now retrieve the columns to update */
876         first = 1;
877         while ((newparam = va_arg(ap, const char *))) {
878                 newval = va_arg(ap, const char *);
879
880                 /* If the column is not within the table, then skip it */
881                 if (!find_column(table, newparam)) {
882                         ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", newparam, tablename, database);
883                         continue;
884                 }
885
886                 ESCAPE_STRING(escapebuf, newval);
887                 if (pgresult) {
888                         ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", newval);
889                         release_table(table);
890                         ast_free(sql);
891                         return -1;
892                 }
893
894                 ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", newparam, ast_str_buffer(escapebuf));
895         }
896         release_table(table);
897
898         ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
899
900         ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
901
902         /* We now have our complete statement; connect to the server and execute it. */
903         if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
904                 ast_mutex_unlock(&pgsql_lock);
905                 return -1;
906         }
907
908         numrows = atoi(PQcmdTuples(result));
909         ast_mutex_unlock(&pgsql_lock);
910
911         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
912
913         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
914          * An integer greater than zero indicates the number of rows affected
915          * Zero indicates that no records were updated
916          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
917          */
918
919         if (numrows >= 0) {
920                 return (int) numrows;
921         }
922
923         return -1;
924 }
925
926 static int store_pgsql(const char *database, const char *table, va_list ap)
927 {
928         PGresult *result = NULL;
929         Oid insertid;
930         struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
931         struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
932         struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
933         int pgresult;
934         const char *newparam, *newval;
935
936         if (!table) {
937                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
938                 return -1;
939         }
940
941         /* Get the first parameter and first value in our list of passed paramater/value pairs */
942         newparam = va_arg(ap, const char *);
943         newval = va_arg(ap, const char *);
944         if (!newparam || !newval) {
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, newparam);
964         ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
965         ESCAPE_STRING(buf, newval);
966         ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
967         while ((newparam = va_arg(ap, const char *))) {
968                 newval = va_arg(ap, const char *);
969                 ESCAPE_STRING(buf, newparam);
970                 ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
971                 ESCAPE_STRING(buf, newval);
972                 ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
973         }
974         va_end(ap);
975         ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
976
977         ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
978
979         if (pgsql_exec(database, table, ast_str_buffer(sql1), &result) != 0) {
980                 ast_mutex_unlock(&pgsql_lock);
981                 return -1;
982         }
983
984         insertid = PQoidValue(result);
985         PQclear(result);
986         ast_mutex_unlock(&pgsql_lock);
987
988         ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s, id: %u\n", table, insertid);
989
990         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
991          * An integer greater than zero indicates the number of rows affected
992          * Zero indicates that no records were updated
993          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
994          */
995
996         if (insertid >= 0)
997                 return (int) insertid;
998
999         return -1;
1000 }
1001
1002 static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
1003 {
1004         PGresult *result = NULL;
1005         int numrows = 0;
1006         int pgresult;
1007         struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
1008         struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
1009         const char *newparam, *newval;
1010
1011         if (!table) {
1012                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
1013                 return -1;
1014         }
1015
1016         /* Get the first parameter and first value in our list of passed paramater/value pairs */
1017         /*newparam = va_arg(ap, const char *);
1018         newval = va_arg(ap, const char *);
1019         if (!newparam || !newval) {*/
1020         if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup))  {
1021                 ast_log(LOG_WARNING,
1022                                 "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
1023                 if (pgsqlConn) {
1024                         PQfinish(pgsqlConn);
1025                         pgsqlConn = NULL;
1026                 };
1027                 return -1;
1028         }
1029
1030         /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
1031         ast_mutex_lock(&pgsql_lock);
1032         if (!pgsql_reconnect(database)) {
1033                 ast_mutex_unlock(&pgsql_lock);
1034                 return -1;
1035         }
1036
1037
1038         /* Create the first part of the query using the first parameter/value pairs we just extracted
1039            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
1040
1041         ESCAPE_STRING(buf1, keyfield);
1042         ESCAPE_STRING(buf2, lookup);
1043         ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
1044         while ((newparam = va_arg(ap, const char *))) {
1045                 newval = va_arg(ap, const char *);
1046                 ESCAPE_STRING(buf1, newparam);
1047                 ESCAPE_STRING(buf2, newval);
1048                 ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
1049         }
1050         va_end(ap);
1051
1052         ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
1053
1054         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
1055                 ast_mutex_unlock(&pgsql_lock);
1056                 return -1;
1057         }
1058
1059         numrows = atoi(PQcmdTuples(result));
1060         ast_mutex_unlock(&pgsql_lock);
1061
1062         ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
1063
1064         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
1065          * An integer greater than zero indicates the number of rows affected
1066          * Zero indicates that no records were updated
1067          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
1068          */
1069
1070         if (numrows >= 0)
1071                 return (int) numrows;
1072
1073         return -1;
1074 }
1075
1076
1077 static struct ast_config *config_pgsql(const char *database, const char *table,
1078                                                                            const char *file, struct ast_config *cfg,
1079                                                                            struct ast_flags flags, const char *suggested_incl, const char *who_asked)
1080 {
1081         PGresult *result = NULL;
1082         long num_rows;
1083         struct ast_variable *new_v;
1084         struct ast_category *cur_cat = NULL;
1085         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
1086         char last[80] = "";
1087         int last_cat_metric = 0;
1088
1089         last[0] = '\0';
1090
1091         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
1092                 ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
1093                 return NULL;
1094         }
1095
1096         ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
1097                         "WHERE filename='%s' and commented=0 "
1098                         "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
1099
1100         ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
1101
1102         ast_mutex_lock(&pgsql_lock);
1103
1104         /* We now have our complete statement; Lets connect to the server and execute it. */
1105         if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
1106                 ast_mutex_unlock(&pgsql_lock);
1107                 return NULL;
1108         }
1109
1110         if ((num_rows = PQntuples(result)) > 0) {
1111                 int rowIndex = 0;
1112
1113                 ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
1114
1115                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
1116                         char *field_category = PQgetvalue(result, rowIndex, 0);
1117                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
1118                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
1119                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
1120                         if (!strcmp(field_var_name, "#include")) {
1121                                 if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
1122                                         PQclear(result);
1123                                         ast_mutex_unlock(&pgsql_lock);
1124                                         return NULL;
1125                                 }
1126                                 continue;
1127                         }
1128
1129                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
1130                                 cur_cat = ast_category_new(field_category, "", 99999);
1131                                 if (!cur_cat)
1132                                         break;
1133                                 strcpy(last, field_category);
1134                                 last_cat_metric = atoi(field_cat_metric);
1135                                 ast_category_append(cfg, cur_cat);
1136                         }
1137                         new_v = ast_variable_new(field_var_name, field_var_val, "");
1138                         ast_variable_append(cur_cat, new_v);
1139                 }
1140         } else {
1141                 ast_log(LOG_WARNING,
1142                                 "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
1143         }
1144
1145         PQclear(result);
1146         ast_mutex_unlock(&pgsql_lock);
1147
1148         return cfg;
1149 }
1150
1151 static int require_pgsql(const char *database, const char *tablename, va_list ap)
1152 {
1153         struct columns *column;
1154         struct tables *table = find_table(database, tablename);
1155         char *elm;
1156         int type, size, res = 0;
1157
1158         if (!table) {
1159                 ast_log(LOG_WARNING, "Table %s not found in database.  This table should exist if you're using realtime.\n", tablename);
1160                 return -1;
1161         }
1162
1163         while ((elm = va_arg(ap, char *))) {
1164                 type = va_arg(ap, require_type);
1165                 size = va_arg(ap, int);
1166                 AST_LIST_TRAVERSE(&table->columns, column, list) {
1167                         if (strcmp(column->name, elm) == 0) {
1168                                 /* Char can hold anything, as long as it is large enough */
1169                                 if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
1170                                         if ((size > column->len) && column->len != -1) {
1171                                                 ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
1172                                                 res = -1;
1173                                         }
1174                                 } else if (strncmp(column->type, "int", 3) == 0) {
1175                                         int typesize = atoi(column->type + 3);
1176                                         /* Integers can hold only other integers */
1177                                         if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1178                                                 type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
1179                                                 type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
1180                                                 type == RQ_UINTEGER2) && typesize == 2) {
1181                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1182                                                 res = -1;
1183                                         } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1184                                                 type == RQ_UINTEGER4) && typesize == 4) {
1185                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1186                                                 res = -1;
1187                                         } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
1188                                                 ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
1189                                                         column->name,
1190                                                                 type == RQ_CHAR ? "char" :
1191                                                                 type == RQ_DATETIME ? "datetime" :
1192                                                                 type == RQ_DATE ? "date" :
1193                                                                 type == RQ_FLOAT ? "float" :
1194                                                                 "a rather stiff drink ",
1195                                                         size, column->type);
1196                                                 res = -1;
1197                                         }
1198                                 } else if (strncmp(column->type, "float", 5) == 0) {
1199                                         if (!ast_rq_is_int(type) && type != RQ_FLOAT) {
1200                                                 ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1201                                                 res = -1;
1202                                         }
1203                                 } else if (strncmp(column->type, "timestamp", 9) == 0) {
1204                                         if (type != RQ_DATETIME && type != RQ_DATE) {
1205                                                 ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1206                                                 res = -1;
1207                                         }
1208                                 } else { /* There are other types that no module implements yet */
1209                                         ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
1210                                         res = -1;
1211                                 }
1212                                 break;
1213                         }
1214                 }
1215
1216                 if (!column) {
1217                         if (requirements == RQ_WARN) {
1218                                 ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
1219                         } else {
1220                                 struct ast_str *sql = ast_str_create(100);
1221                                 char fieldtype[15];
1222                                 PGresult *result;
1223
1224                                 if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
1225                                         /* Size is minimum length; make it at least 50% greater,
1226                                          * just to be sure, because PostgreSQL doesn't support
1227                                          * resizing columns. */
1228                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(%d)",
1229                                                 size < 15 ? size * 2 :
1230                                                 (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
1231                                 } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
1232                                         snprintf(fieldtype, sizeof(fieldtype), "INT2");
1233                                 } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
1234                                         snprintf(fieldtype, sizeof(fieldtype), "INT4");
1235                                 } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
1236                                         snprintf(fieldtype, sizeof(fieldtype), "INT8");
1237                                 } else if (type == RQ_UINTEGER8) {
1238                                         /* No such type on PostgreSQL */
1239                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
1240                                 } else if (type == RQ_FLOAT) {
1241                                         snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
1242                                 } else if (type == RQ_DATE) {
1243                                         snprintf(fieldtype, sizeof(fieldtype), "DATE");
1244                                 } else if (type == RQ_DATETIME) {
1245                                         snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
1246                                 } else {
1247                                         ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
1248                                         ast_free(sql);
1249                                         continue;
1250                                 }
1251                                 ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
1252                                 ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
1253
1254                                 ast_mutex_lock(&pgsql_lock);
1255                                 ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
1256
1257                                 if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
1258                                         ast_mutex_unlock(&pgsql_lock);
1259                                         return -1;
1260                                 }
1261
1262                                 ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
1263                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1264                                         ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1265                                 }
1266                                 PQclear(result);
1267                                 ast_mutex_unlock(&pgsql_lock);
1268
1269                                 ast_free(sql);
1270                         }
1271                 }
1272         }
1273         release_table(table);
1274         return res;
1275 }
1276
1277 static int unload_pgsql(const char *database, const char *tablename)
1278 {
1279         struct tables *cur;
1280         ast_debug(2, "About to lock table cache list\n");
1281         AST_LIST_LOCK(&psql_tables);
1282         ast_debug(2, "About to traverse table cache list\n");
1283         AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
1284                 if (strcmp(cur->name, tablename) == 0) {
1285                         ast_debug(2, "About to remove matching cache entry\n");
1286                         AST_LIST_REMOVE_CURRENT(list);
1287                         ast_debug(2, "About to destroy matching cache entry\n");
1288                         destroy_table(cur);
1289                         ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
1290                         break;
1291                 }
1292         }
1293         AST_LIST_TRAVERSE_SAFE_END
1294         AST_LIST_UNLOCK(&psql_tables);
1295         ast_debug(2, "About to return\n");
1296         return cur ? 0 : -1;
1297 }
1298
1299 static struct ast_config_engine pgsql_engine = {
1300         .name = "pgsql",
1301         .load_func = config_pgsql,
1302         .realtime_func = realtime_pgsql,
1303         .realtime_multi_func = realtime_multi_pgsql,
1304         .store_func = store_pgsql,
1305         .destroy_func = destroy_pgsql,
1306         .update_func = update_pgsql,
1307         .update2_func = update2_pgsql,
1308         .require_func = require_pgsql,
1309         .unload_func = unload_pgsql,
1310 };
1311
1312 static int load_module(void)
1313 {
1314         if(!parse_config(0))
1315                 return AST_MODULE_LOAD_DECLINE;
1316
1317         ast_config_engine_register(&pgsql_engine);
1318         ast_verb(1, "PostgreSQL RealTime driver loaded.\n");
1319         ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1320
1321         return 0;
1322 }
1323
1324 static int unload_module(void)
1325 {
1326         struct tables *table;
1327         /* Acquire control before doing anything to the module itself. */
1328         ast_mutex_lock(&pgsql_lock);
1329
1330         if (pgsqlConn) {
1331                 PQfinish(pgsqlConn);
1332                 pgsqlConn = NULL;
1333         }
1334         ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1335         ast_config_engine_deregister(&pgsql_engine);
1336         ast_verb(1, "PostgreSQL RealTime unloaded.\n");
1337
1338         /* Destroy cached table info */
1339         AST_LIST_LOCK(&psql_tables);
1340         while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
1341                 destroy_table(table);
1342         }
1343         AST_LIST_UNLOCK(&psql_tables);
1344
1345         /* Unlock so something else can destroy the lock. */
1346         ast_mutex_unlock(&pgsql_lock);
1347
1348         return 0;
1349 }
1350
1351 static int reload(void)
1352 {
1353         parse_config(1);
1354
1355         return 0;
1356 }
1357
1358 static int parse_config(int is_reload)
1359 {
1360         struct ast_config *config;
1361         const char *s;
1362         struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1363
1364         config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
1365         if (config == CONFIG_STATUS_FILEUNCHANGED) {
1366                 return 0;
1367         }
1368
1369         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1370                 ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
1371                 return 0;
1372         }
1373
1374         ast_mutex_lock(&pgsql_lock);
1375
1376         if (pgsqlConn) {
1377                 PQfinish(pgsqlConn);
1378                 pgsqlConn = NULL;
1379         }
1380
1381         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
1382                 ast_log(LOG_WARNING,
1383                                 "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
1384                 strcpy(dbuser, "asterisk");
1385         } else {
1386                 ast_copy_string(dbuser, s, sizeof(dbuser));
1387         }
1388
1389         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
1390                 ast_log(LOG_WARNING,
1391                                 "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
1392                 strcpy(dbpass, "asterisk");
1393         } else {
1394                 ast_copy_string(dbpass, s, sizeof(dbpass));
1395         }
1396
1397         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
1398                 ast_log(LOG_WARNING,
1399                                 "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
1400                 dbhost[0] = '\0';
1401         } else {
1402                 ast_copy_string(dbhost, s, sizeof(dbhost));
1403         }
1404
1405         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
1406                 ast_log(LOG_WARNING,
1407                                 "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
1408                 strcpy(dbname, "asterisk");
1409         } else {
1410                 ast_copy_string(dbname, s, sizeof(dbname));
1411         }
1412
1413         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
1414                 ast_log(LOG_WARNING,
1415                                 "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
1416                 dbport = 5432;
1417         } else {
1418                 dbport = atoi(s);
1419         }
1420
1421         if (!ast_strlen_zero(dbhost)) {
1422                 /* No socket needed */
1423         } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
1424                 ast_log(LOG_WARNING,
1425                                 "PostgreSQL RealTime: No database socket found, using '/tmp/.s.PGSQL.%d' as default.\n", dbport);
1426                 strcpy(dbsock, "/tmp");
1427         } else {
1428                 ast_copy_string(dbsock, s, sizeof(dbsock));
1429         }
1430
1431         if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
1432                 ast_log(LOG_WARNING,
1433                                 "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
1434                 requirements = RQ_WARN;
1435         } else if (!strcasecmp(s, "createclose")) {
1436                 requirements = RQ_CREATECLOSE;
1437         } else if (!strcasecmp(s, "createchar")) {
1438                 requirements = RQ_CREATECHAR;
1439         }
1440
1441         ast_config_destroy(config);
1442
1443         if (option_debug) {
1444                 if (!ast_strlen_zero(dbhost)) {
1445                         ast_debug(1, "PostgreSQL RealTime Host: %s\n", dbhost);
1446                         ast_debug(1, "PostgreSQL RealTime Port: %i\n", dbport);
1447                 } else {
1448                         ast_debug(1, "PostgreSQL RealTime Socket: %s\n", dbsock);
1449                 }
1450                 ast_debug(1, "PostgreSQL RealTime User: %s\n", dbuser);
1451                 ast_debug(1, "PostgreSQL RealTime Password: %s\n", dbpass);
1452                 ast_debug(1, "PostgreSQL RealTime DBName: %s\n", dbname);
1453         }
1454
1455         if (!pgsql_reconnect(NULL)) {
1456                 ast_log(LOG_WARNING,
1457                                 "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
1458                 ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
1459         }
1460
1461         ast_verb(2, "PostgreSQL RealTime reloaded.\n");
1462
1463         /* Done reloading. Release lock so others can now use driver. */
1464         ast_mutex_unlock(&pgsql_lock);
1465
1466         return 1;
1467 }
1468
1469 static int pgsql_reconnect(const char *database)
1470 {
1471         char my_database[50];
1472
1473         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
1474
1475         /* mutex lock should have been locked before calling this function. */
1476
1477         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
1478                 PQfinish(pgsqlConn);
1479                 pgsqlConn = NULL;
1480         }
1481
1482         /* DB password can legitimately be 0-length */
1483         if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
1484                 struct ast_str *connInfo = ast_str_create(32);
1485
1486                 ast_str_set(&connInfo, 0, "host=%s port=%d dbname=%s user=%s",
1487                         S_OR(dbhost, dbsock), dbport, my_database, dbuser);
1488                 if (!ast_strlen_zero(dbpass))
1489                         ast_str_append(&connInfo, 0, " password=%s", dbpass);
1490
1491                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1492                 pgsqlConn = PQconnectdb(ast_str_buffer(connInfo));
1493                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1494                 ast_free(connInfo);
1495                 connInfo = NULL;
1496
1497                 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
1498                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1499                         ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
1500                         connect_time = time(NULL);
1501                         version = PQserverVersion(pgsqlConn);
1502                         return 1;
1503                 } else {
1504                         ast_log(LOG_ERROR,
1505                                         "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
1506                                         dbname, dbhost, PQresultErrorMessage(NULL));
1507                         return 0;
1508                 }
1509         } else {
1510                 ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
1511                 return 1;
1512         }
1513 }
1514
1515 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1516 {
1517         struct tables *cur;
1518         int l, which;
1519         char *ret = NULL;
1520
1521         switch (cmd) {
1522         case CLI_INIT:
1523                 e->command = "realtime show pgsql cache";
1524                 e->usage =
1525                         "Usage: realtime show pgsql cache [<table>]\n"
1526                         "       Shows table cache for the PostgreSQL RealTime driver\n";
1527                 return NULL;
1528         case CLI_GENERATE:
1529                 if (a->argc != 4) {
1530                         return NULL;
1531                 }
1532                 l = strlen(a->word);
1533                 which = 0;
1534                 AST_LIST_LOCK(&psql_tables);
1535                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1536                         if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
1537                                 ret = ast_strdup(cur->name);
1538                                 break;
1539                         }
1540                 }
1541                 AST_LIST_UNLOCK(&psql_tables);
1542                 return ret;
1543         }
1544
1545         if (a->argc == 4) {
1546                 /* List of tables */
1547                 AST_LIST_LOCK(&psql_tables);
1548                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1549                         ast_cli(a->fd, "%s\n", cur->name);
1550                 }
1551                 AST_LIST_UNLOCK(&psql_tables);
1552         } else if (a->argc == 5) {
1553                 /* List of columns */
1554                 if ((cur = find_table(NULL, a->argv[4]))) {
1555                         struct columns *col;
1556                         ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
1557                         ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
1558                         AST_LIST_TRAVERSE(&cur->columns, col, list) {
1559                                 ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
1560                         }
1561                         release_table(cur);
1562                 } else {
1563                         ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
1564                 }
1565         }
1566         return 0;
1567 }
1568
1569 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1570 {
1571         char status[256], credentials[100] = "";
1572         int ctimesec = time(NULL) - connect_time;
1573
1574         switch (cmd) {
1575         case CLI_INIT:
1576                 e->command = "realtime show pgsql status";
1577                 e->usage =
1578                         "Usage: realtime show pgsql status\n"
1579                         "       Shows connection information for the PostgreSQL RealTime driver\n";
1580                 return NULL;
1581         case CLI_GENERATE:
1582                 return NULL;
1583         }
1584
1585         if (a->argc != 4)
1586                 return CLI_SHOWUSAGE;
1587
1588         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1589                 if (!ast_strlen_zero(dbhost))
1590                         snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
1591                 else if (!ast_strlen_zero(dbsock))
1592                         snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
1593                 else
1594                         snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
1595
1596                 if (!ast_strlen_zero(dbuser))
1597                         snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
1598
1599                 if (ctimesec > 31536000)
1600                         ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1601                                         status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
1602                                         (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1603                 else if (ctimesec > 86400)
1604                         ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
1605                                         credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
1606                                         ctimesec % 60);
1607                 else if (ctimesec > 3600)
1608                         ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
1609                                         ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1610                 else if (ctimesec > 60)
1611                         ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
1612                                         ctimesec % 60);
1613                 else
1614                         ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1615
1616                 return CLI_SUCCESS;
1617         } else {
1618                 return CLI_FAILURE;
1619         }
1620 }
1621
1622 /* needs usecount semantics defined */
1623 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL RealTime Configuration Driver",
1624                 .load = load_module,
1625                 .unload = unload_module,
1626                 .reload = reload,
1627                 .load_pri = AST_MODPRI_REALTIME_DRIVER,
1628                );