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