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