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