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