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