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