fixes pgsql double free of threadstorage
[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  * \extref PostgreSQL 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                 return -1;
682         } else {
683                 ExecStatusType result_status = PQresultStatus(result);
684                 if (result_status != PGRES_COMMAND_OK
685                         && result_status != PGRES_TUPLES_OK
686                         && result_status != PGRES_NONFATAL_ERROR) {
687                         ast_log(LOG_WARNING,
688                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
689                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
690                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
691                                                 PQresultErrorMessage(result), PQresStatus(result_status));
692                         ast_mutex_unlock(&pgsql_lock);
693                         return -1;
694                 }
695         }
696
697         numrows = atoi(PQcmdTuples(result));
698         ast_mutex_unlock(&pgsql_lock);
699
700         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
701
702         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
703          * An integer greater than zero indicates the number of rows affected
704          * Zero indicates that no records were updated
705          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
706          */
707
708         if (numrows >= 0)
709                 return (int) numrows;
710
711         return -1;
712 }
713
714 static int update2_pgsql(const char *database, const char *tablename, va_list ap)
715 {
716         PGresult *result = NULL;
717         int numrows = 0, pgresult, first = 1;
718         struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
719         const char *newparam, *newval;
720         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
721         struct ast_str *where = ast_str_thread_get(&where_buf, 100);
722         struct tables *table;
723
724         if (!tablename) {
725                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
726                 return -1;
727         }
728
729         if (!escapebuf || !sql || !where) {
730                 /* Memory error, already handled */
731                 return -1;
732         }
733
734         if (!(table = find_table(tablename))) {
735                 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
736                 return -1;
737         }
738
739         ast_str_set(&sql, 0, "UPDATE %s SET ", tablename);
740         ast_str_set(&where, 0, "WHERE");
741
742         while ((newparam = va_arg(ap, const char *))) {
743                 if (!find_column(table, newparam)) {
744                         ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", newparam, tablename, database);
745                         release_table(table);
746                         return -1;
747                 }
748                         
749                 newval = va_arg(ap, const char *);
750                 ESCAPE_STRING(escapebuf, newval);
751                 if (pgresult) {
752                         ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
753                         release_table(table);
754                         ast_free(sql);
755                         return -1;
756                 }
757                 ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", newparam, ast_str_buffer(escapebuf));
758                 first = 0;
759         }
760
761         if (first) {
762                 ast_log(LOG_WARNING,
763                                 "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
764                 if (pgsqlConn) {
765                         PQfinish(pgsqlConn);
766                         pgsqlConn = NULL;
767                 }
768                 release_table(table);
769                 return -1;
770         }
771
772         /* Now retrieve the columns to update */
773         first = 1;
774         while ((newparam = va_arg(ap, const char *))) {
775                 newval = va_arg(ap, const char *);
776
777                 /* If the column is not within the table, then skip it */
778                 if (!find_column(table, newparam)) {
779                         ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", newparam, tablename, database);
780                         continue;
781                 }
782
783                 ESCAPE_STRING(escapebuf, newval);
784                 if (pgresult) {
785                         ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
786                         release_table(table);
787                         ast_free(sql);
788                         return -1;
789                 }
790
791                 ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", newparam, ast_str_buffer(escapebuf));
792         }
793         release_table(table);
794
795         ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
796
797         ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
798
799         /* We now have our complete statement; connect to the server and execute it. */
800         ast_mutex_lock(&pgsql_lock);
801         if (!pgsql_reconnect(database)) {
802                 ast_mutex_unlock(&pgsql_lock);
803                 return -1;
804         }
805
806         if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
807                 ast_log(LOG_WARNING,
808                                 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
809                 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
810                 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
811                 ast_mutex_unlock(&pgsql_lock);
812                 return -1;
813         } else {
814                 ExecStatusType result_status = PQresultStatus(result);
815                 if (result_status != PGRES_COMMAND_OK
816                         && result_status != PGRES_TUPLES_OK
817                         && result_status != PGRES_NONFATAL_ERROR) {
818                         ast_log(LOG_WARNING,
819                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
820                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
821                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
822                                                 PQresultErrorMessage(result), PQresStatus(result_status));
823                         ast_mutex_unlock(&pgsql_lock);
824                         return -1;
825                 }
826         }
827
828         numrows = atoi(PQcmdTuples(result));
829         ast_mutex_unlock(&pgsql_lock);
830
831         ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
832
833         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
834          * An integer greater than zero indicates the number of rows affected
835          * Zero indicates that no records were updated
836          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
837          */
838
839         if (numrows >= 0) {
840                 return (int) numrows;
841         }
842
843         return -1;
844 }
845
846 static int store_pgsql(const char *database, const char *table, va_list ap)
847 {
848         PGresult *result = NULL;
849         Oid insertid;
850         struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
851         struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
852         struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
853         int pgresult;
854         const char *newparam, *newval;
855
856         if (!table) {
857                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
858                 return -1;
859         }
860
861         /* Get the first parameter and first value in our list of passed paramater/value pairs */
862         newparam = va_arg(ap, const char *);
863         newval = va_arg(ap, const char *);
864         if (!newparam || !newval) {
865                 ast_log(LOG_WARNING,
866                                 "PostgreSQL RealTime: Realtime storage requires at least 1 parameter and 1 value to store.\n");
867                 if (pgsqlConn) {
868                         PQfinish(pgsqlConn);
869                         pgsqlConn = NULL;
870                 }
871                 return -1;
872         }
873
874         /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
875         ast_mutex_lock(&pgsql_lock);
876         if (!pgsql_reconnect(database)) {
877                 ast_mutex_unlock(&pgsql_lock);
878                 return -1;
879         }
880
881         /* Create the first part of the query using the first parameter/value pairs we just extracted
882            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
883         ESCAPE_STRING(buf, newparam);
884         ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
885         ESCAPE_STRING(buf, newval);
886         ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
887         while ((newparam = va_arg(ap, const char *))) {
888                 newval = va_arg(ap, const char *);
889                 ESCAPE_STRING(buf, newparam);
890                 ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
891                 ESCAPE_STRING(buf, newval);
892                 ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
893         }
894         va_end(ap);
895         ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
896
897         ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
898
899         if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql1)))) {
900                 ast_log(LOG_WARNING,
901                                 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
902                 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
903                 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
904                 ast_mutex_unlock(&pgsql_lock);
905                 return -1;
906         } else {
907                 ExecStatusType result_status = PQresultStatus(result);
908                 if (result_status != PGRES_COMMAND_OK
909                         && result_status != PGRES_TUPLES_OK
910                         && result_status != PGRES_NONFATAL_ERROR) {
911                         ast_log(LOG_WARNING,
912                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
913                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
914                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
915                                                 PQresultErrorMessage(result), PQresStatus(result_status));
916                         ast_mutex_unlock(&pgsql_lock);
917                         return -1;
918                 }
919         }
920
921         insertid = PQoidValue(result);
922         ast_mutex_unlock(&pgsql_lock);
923
924         ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s, id: %u\n", table, insertid);
925
926         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
927          * An integer greater than zero indicates the number of rows affected
928          * Zero indicates that no records were updated
929          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
930          */
931
932         if (insertid >= 0)
933                 return (int) insertid;
934
935         return -1;
936 }
937
938 static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
939 {
940         PGresult *result = NULL;
941         int numrows = 0;
942         int pgresult;
943         struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
944         struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
945         const char *newparam, *newval;
946
947         if (!table) {
948                 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
949                 return -1;
950         }
951
952         /* Get the first parameter and first value in our list of passed paramater/value pairs */
953         /*newparam = va_arg(ap, const char *);
954         newval = va_arg(ap, const char *);
955         if (!newparam || !newval) {*/
956         if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup))  {
957                 ast_log(LOG_WARNING,
958                                 "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
959                 if (pgsqlConn) {
960                         PQfinish(pgsqlConn);
961                         pgsqlConn = NULL;
962                 };
963                 return -1;
964         }
965
966         /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
967         ast_mutex_lock(&pgsql_lock);
968         if (!pgsql_reconnect(database)) {
969                 ast_mutex_unlock(&pgsql_lock);
970                 return -1;
971         }
972
973
974         /* Create the first part of the query using the first parameter/value pairs we just extracted
975            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
976
977         ESCAPE_STRING(buf1, keyfield);
978         ESCAPE_STRING(buf2, lookup);
979         ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
980         while ((newparam = va_arg(ap, const char *))) {
981                 newval = va_arg(ap, const char *);
982                 ESCAPE_STRING(buf1, newparam);
983                 ESCAPE_STRING(buf2, newval);
984                 ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
985         }
986         va_end(ap);
987
988         ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
989
990         if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
991                 ast_log(LOG_WARNING,
992                                 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
993                 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
994                 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
995                 ast_mutex_unlock(&pgsql_lock);
996                 return -1;
997         } else {
998                 ExecStatusType result_status = PQresultStatus(result);
999                 if (result_status != PGRES_COMMAND_OK
1000                         && result_status != PGRES_TUPLES_OK
1001                         && result_status != PGRES_NONFATAL_ERROR) {
1002                         ast_log(LOG_WARNING,
1003                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
1004                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1005                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
1006                                                 PQresultErrorMessage(result), PQresStatus(result_status));
1007                         ast_mutex_unlock(&pgsql_lock);
1008                         return -1;
1009                 }
1010         }
1011
1012         numrows = atoi(PQcmdTuples(result));
1013         ast_mutex_unlock(&pgsql_lock);
1014
1015         ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
1016
1017         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
1018          * An integer greater than zero indicates the number of rows affected
1019          * Zero indicates that no records were updated
1020          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
1021          */
1022
1023         if (numrows >= 0)
1024                 return (int) numrows;
1025
1026         return -1;
1027 }
1028
1029
1030 static struct ast_config *config_pgsql(const char *database, const char *table,
1031                                                                            const char *file, struct ast_config *cfg,
1032                                                                            struct ast_flags flags, const char *suggested_incl, const char *who_asked)
1033 {
1034         PGresult *result = NULL;
1035         long num_rows;
1036         struct ast_variable *new_v;
1037         struct ast_category *cur_cat = NULL;
1038         struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
1039         char last[80] = "";
1040         int last_cat_metric = 0;
1041
1042         last[0] = '\0';
1043
1044         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
1045                 ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
1046                 return NULL;
1047         }
1048
1049         ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
1050                         "WHERE filename='%s' and commented=0"
1051                         "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
1052
1053         ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
1054
1055         /* We now have our complete statement; Lets connect to the server and execute it. */
1056         ast_mutex_lock(&pgsql_lock);
1057         if (!pgsql_reconnect(database)) {
1058                 ast_mutex_unlock(&pgsql_lock);
1059                 return NULL;
1060         }
1061
1062         if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
1063                 ast_log(LOG_WARNING,
1064                                 "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", table, database);
1065                 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1066                 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
1067                 ast_mutex_unlock(&pgsql_lock);
1068                 return NULL;
1069         } else {
1070                 ExecStatusType result_status = PQresultStatus(result);
1071                 if (result_status != PGRES_COMMAND_OK
1072                         && result_status != PGRES_TUPLES_OK
1073                         && result_status != PGRES_NONFATAL_ERROR) {
1074                         ast_log(LOG_WARNING,
1075                                         "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
1076                         ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1077                         ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
1078                                                 PQresultErrorMessage(result), PQresStatus(result_status));
1079                         ast_mutex_unlock(&pgsql_lock);
1080                         return NULL;
1081                 }
1082         }
1083
1084         if ((num_rows = PQntuples(result)) > 0) {
1085                 int rowIndex = 0;
1086
1087                 ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
1088
1089                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
1090                         char *field_category = PQgetvalue(result, rowIndex, 0);
1091                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
1092                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
1093                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
1094                         if (!strcmp(field_var_name, "#include")) {
1095                                 if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
1096                                         PQclear(result);
1097                                         ast_mutex_unlock(&pgsql_lock);
1098                                         return NULL;
1099                                 }
1100                                 continue;
1101                         }
1102
1103                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
1104                                 cur_cat = ast_category_new(field_category, "", 99999);
1105                                 if (!cur_cat)
1106                                         break;
1107                                 strcpy(last, field_category);
1108                                 last_cat_metric = atoi(field_cat_metric);
1109                                 ast_category_append(cfg, cur_cat);
1110                         }
1111                         new_v = ast_variable_new(field_var_name, field_var_val, "");
1112                         ast_variable_append(cur_cat, new_v);
1113                 }
1114         } else {
1115                 ast_log(LOG_WARNING,
1116                                 "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
1117         }
1118
1119         PQclear(result);
1120         ast_mutex_unlock(&pgsql_lock);
1121
1122         return cfg;
1123 }
1124
1125 static int require_pgsql(const char *database, const char *tablename, va_list ap)
1126 {
1127         struct columns *column;
1128         struct tables *table = find_table(tablename);
1129         char *elm;
1130         int type, size, res = 0;
1131
1132         if (!table) {
1133                 ast_log(LOG_WARNING, "Table %s not found in database.  This table should exist if you're using realtime.\n", tablename);
1134                 return -1;
1135         }
1136
1137         while ((elm = va_arg(ap, char *))) {
1138                 type = va_arg(ap, require_type);
1139                 size = va_arg(ap, int);
1140                 AST_LIST_TRAVERSE(&table->columns, column, list) {
1141                         if (strcmp(column->name, elm) == 0) {
1142                                 /* Char can hold anything, as long as it is large enough */
1143                                 if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
1144                                         if ((size > column->len) && column->len != -1) {
1145                                                 ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
1146                                                 res = -1;
1147                                         }
1148                                 } else if (strncmp(column->type, "int", 3) == 0) {
1149                                         int typesize = atoi(column->type + 3);
1150                                         /* Integers can hold only other integers */
1151                                         if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1152                                                 type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
1153                                                 type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
1154                                                 type == RQ_UINTEGER2) && typesize == 2) {
1155                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1156                                                 res = -1;
1157                                         } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1158                                                 type == RQ_UINTEGER4) && typesize == 4) {
1159                                                 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1160                                                 res = -1;
1161                                         } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
1162                                                 ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
1163                                                         column->name,
1164                                                                 type == RQ_CHAR ? "char" :
1165                                                                 type == RQ_DATETIME ? "datetime" :
1166                                                                 type == RQ_DATE ? "date" :
1167                                                                 type == RQ_FLOAT ? "float" :
1168                                                                 "a rather stiff drink ",
1169                                                         size, column->type);
1170                                                 res = -1;
1171                                         }
1172                                 } else if (strncmp(column->type, "float", 5) == 0 && !ast_rq_is_int(type) && type != RQ_FLOAT) {
1173                                         ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1174                                         res = -1;
1175                                 } else { /* There are other types that no module implements yet */
1176                                         ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
1177                                         res = -1;
1178                                 }
1179                                 break;
1180                         }
1181                 }
1182
1183                 if (!column) {
1184                         if (requirements == RQ_WARN) {
1185                                 ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
1186                         } else {
1187                                 struct ast_str *sql = ast_str_create(100);
1188                                 char fieldtype[15];
1189                                 PGresult *result;
1190
1191                                 if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
1192                                         /* Size is minimum length; make it at least 50% greater,
1193                                          * just to be sure, because PostgreSQL doesn't support
1194                                          * resizing columns. */
1195                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(%d)",
1196                                                 size < 15 ? size * 2 :
1197                                                 (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
1198                                 } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
1199                                         snprintf(fieldtype, sizeof(fieldtype), "INT2");
1200                                 } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
1201                                         snprintf(fieldtype, sizeof(fieldtype), "INT4");
1202                                 } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
1203                                         snprintf(fieldtype, sizeof(fieldtype), "INT8");
1204                                 } else if (type == RQ_UINTEGER8) {
1205                                         /* No such type on PostgreSQL */
1206                                         snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
1207                                 } else if (type == RQ_FLOAT) {
1208                                         snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
1209                                 } else if (type == RQ_DATE) {
1210                                         snprintf(fieldtype, sizeof(fieldtype), "DATE");
1211                                 } else if (type == RQ_DATETIME) {
1212                                         snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
1213                                 } else {
1214                                         ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
1215                                         ast_free(sql);
1216                                         continue;
1217                                 }
1218                                 ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
1219                                 ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
1220
1221                                 ast_mutex_lock(&pgsql_lock);
1222                                 if (!pgsql_reconnect(database)) {
1223                                         ast_mutex_unlock(&pgsql_lock);
1224                                         ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1225                                         ast_free(sql);
1226                                         continue;
1227                                 }
1228
1229                                 ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
1230                                 result = PQexec(pgsqlConn, ast_str_buffer(sql));
1231                                 ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
1232                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1233                                         ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1234                                 }
1235                                 PQclear(result);
1236                                 ast_mutex_unlock(&pgsql_lock);
1237
1238                                 ast_free(sql);
1239                         }
1240                 }
1241         }
1242         release_table(table);
1243         return res;
1244 }
1245
1246 static int unload_pgsql(const char *database, const char *tablename)
1247 {
1248         struct tables *cur;
1249         ast_debug(2, "About to lock table cache list\n");
1250         AST_LIST_LOCK(&psql_tables);
1251         ast_debug(2, "About to traverse table cache list\n");
1252         AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
1253                 if (strcmp(cur->name, tablename) == 0) {
1254                         ast_debug(2, "About to remove matching cache entry\n");
1255                         AST_LIST_REMOVE_CURRENT(list);
1256                         ast_debug(2, "About to destroy matching cache entry\n");
1257                         destroy_table(cur);
1258                         ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
1259                         break;
1260                 }
1261         }
1262         AST_LIST_TRAVERSE_SAFE_END
1263         AST_LIST_UNLOCK(&psql_tables);
1264         ast_debug(2, "About to return\n");
1265         return cur ? 0 : -1;
1266 }
1267
1268 static struct ast_config_engine pgsql_engine = {
1269         .name = "pgsql",
1270         .load_func = config_pgsql,
1271         .realtime_func = realtime_pgsql,
1272         .realtime_multi_func = realtime_multi_pgsql,
1273         .store_func = store_pgsql,
1274         .destroy_func = destroy_pgsql,
1275         .update_func = update_pgsql,
1276         .update2_func = update2_pgsql,
1277         .require_func = require_pgsql,
1278         .unload_func = unload_pgsql,
1279 };
1280
1281 static int load_module(void)
1282 {
1283         if(!parse_config(0))
1284                 return AST_MODULE_LOAD_DECLINE;
1285
1286         ast_config_engine_register(&pgsql_engine);
1287         ast_verb(1, "PostgreSQL RealTime driver loaded.\n");
1288         ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1289
1290         return 0;
1291 }
1292
1293 static int unload_module(void)
1294 {
1295         struct tables *table;
1296         /* Acquire control before doing anything to the module itself. */
1297         ast_mutex_lock(&pgsql_lock);
1298
1299         if (pgsqlConn) {
1300                 PQfinish(pgsqlConn);
1301                 pgsqlConn = NULL;
1302         }
1303         ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1304         ast_config_engine_deregister(&pgsql_engine);
1305         ast_verb(1, "PostgreSQL RealTime unloaded.\n");
1306
1307         /* Destroy cached table info */
1308         AST_LIST_LOCK(&psql_tables);
1309         while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
1310                 destroy_table(table);
1311         }
1312         AST_LIST_UNLOCK(&psql_tables);
1313
1314         /* Unlock so something else can destroy the lock. */
1315         ast_mutex_unlock(&pgsql_lock);
1316
1317         return 0;
1318 }
1319
1320 static int reload(void)
1321 {
1322         parse_config(1);
1323
1324         return 0;
1325 }
1326
1327 static int parse_config(int is_reload)
1328 {
1329         struct ast_config *config;
1330         const char *s;
1331         struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1332
1333         config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
1334         if (config == CONFIG_STATUS_FILEUNCHANGED) {
1335                 return 0;
1336         }
1337
1338         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1339                 ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
1340                 return 0;
1341         }
1342
1343         ast_mutex_lock(&pgsql_lock);
1344
1345         if (pgsqlConn) {
1346                 PQfinish(pgsqlConn);
1347                 pgsqlConn = NULL;
1348         }
1349
1350         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
1351                 ast_log(LOG_WARNING,
1352                                 "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
1353                 strcpy(dbuser, "asterisk");
1354         } else {
1355                 ast_copy_string(dbuser, s, sizeof(dbuser));
1356         }
1357
1358         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
1359                 ast_log(LOG_WARNING,
1360                                 "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
1361                 strcpy(dbpass, "asterisk");
1362         } else {
1363                 ast_copy_string(dbpass, s, sizeof(dbpass));
1364         }
1365
1366         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
1367                 ast_log(LOG_WARNING,
1368                                 "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
1369                 dbhost[0] = '\0';
1370         } else {
1371                 ast_copy_string(dbhost, s, sizeof(dbhost));
1372         }
1373
1374         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
1375                 ast_log(LOG_WARNING,
1376                                 "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
1377                 strcpy(dbname, "asterisk");
1378         } else {
1379                 ast_copy_string(dbname, s, sizeof(dbname));
1380         }
1381
1382         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
1383                 ast_log(LOG_WARNING,
1384                                 "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
1385                 dbport = 5432;
1386         } else {
1387                 dbport = atoi(s);
1388         }
1389
1390         if (!ast_strlen_zero(dbhost)) {
1391                 /* No socket needed */
1392         } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
1393                 ast_log(LOG_WARNING,
1394                                 "PostgreSQL RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
1395                 strcpy(dbsock, "/tmp/pgsql.sock");
1396         } else {
1397                 ast_copy_string(dbsock, s, sizeof(dbsock));
1398         }
1399
1400         if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
1401                 ast_log(LOG_WARNING,
1402                                 "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
1403                 requirements = RQ_WARN;
1404         } else if (!strcasecmp(s, "createclose")) {
1405                 requirements = RQ_CREATECLOSE;
1406         } else if (!strcasecmp(s, "createchar")) {
1407                 requirements = RQ_CREATECHAR;
1408         }
1409
1410         ast_config_destroy(config);
1411
1412         if (option_debug) {
1413                 if (!ast_strlen_zero(dbhost)) {
1414                         ast_debug(1, "PostgreSQL RealTime Host: %s\n", dbhost);
1415                         ast_debug(1, "PostgreSQL RealTime Port: %i\n", dbport);
1416                 } else {
1417                         ast_debug(1, "PostgreSQL RealTime Socket: %s\n", dbsock);
1418                 }
1419                 ast_debug(1, "PostgreSQL RealTime User: %s\n", dbuser);
1420                 ast_debug(1, "PostgreSQL RealTime Password: %s\n", dbpass);
1421                 ast_debug(1, "PostgreSQL RealTime DBName: %s\n", dbname);
1422         }
1423
1424         if (!pgsql_reconnect(NULL)) {
1425                 ast_log(LOG_WARNING,
1426                                 "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
1427                 ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
1428         }
1429
1430         ast_verb(2, "PostgreSQL RealTime reloaded.\n");
1431
1432         /* Done reloading. Release lock so others can now use driver. */
1433         ast_mutex_unlock(&pgsql_lock);
1434
1435         return 1;
1436 }
1437
1438 static int pgsql_reconnect(const char *database)
1439 {
1440         char my_database[50];
1441
1442         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
1443
1444         /* mutex lock should have been locked before calling this function. */
1445
1446         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
1447                 PQfinish(pgsqlConn);
1448                 pgsqlConn = NULL;
1449         }
1450
1451         /* DB password can legitimately be 0-length */
1452         if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
1453                 struct ast_str *connInfo = ast_str_create(32);
1454
1455                 ast_str_set(&connInfo, 0, "host=%s port=%d dbname=%s user=%s",
1456                         dbhost, dbport, my_database, dbuser);
1457                 if (!ast_strlen_zero(dbpass))
1458                         ast_str_append(&connInfo, 0, " password=%s", dbpass);
1459
1460                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1461                 pgsqlConn = PQconnectdb(ast_str_buffer(connInfo));
1462                 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1463                 ast_free(connInfo);
1464                 connInfo = NULL;
1465
1466                 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
1467                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1468                         ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
1469                         connect_time = time(NULL);
1470                         version = PQserverVersion(pgsqlConn);
1471                         return 1;
1472                 } else {
1473                         ast_log(LOG_ERROR,
1474                                         "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
1475                                         dbname, dbhost, PQresultErrorMessage(NULL));
1476                         return 0;
1477                 }
1478         } else {
1479                 ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
1480                 return 1;
1481         }
1482 }
1483
1484 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1485 {
1486         struct tables *cur;
1487         int l, which;
1488         char *ret = NULL;
1489
1490         switch (cmd) {
1491         case CLI_INIT:
1492                 e->command = "realtime show pgsql cache";
1493                 e->usage =
1494                         "Usage: realtime show pgsql cache [<table>]\n"
1495                         "       Shows table cache for the PostgreSQL RealTime driver\n";
1496                 return NULL;
1497         case CLI_GENERATE:
1498                 if (a->argc != 4) {
1499                         return NULL;
1500                 }
1501                 l = strlen(a->word);
1502                 which = 0;
1503                 AST_LIST_LOCK(&psql_tables);
1504                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1505                         if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
1506                                 ret = ast_strdup(cur->name);
1507                                 break;
1508                         }
1509                 }
1510                 AST_LIST_UNLOCK(&psql_tables);
1511                 return ret;
1512         }
1513
1514         if (a->argc == 4) {
1515                 /* List of tables */
1516                 AST_LIST_LOCK(&psql_tables);
1517                 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1518                         ast_cli(a->fd, "%s\n", cur->name);
1519                 }
1520                 AST_LIST_UNLOCK(&psql_tables);
1521         } else if (a->argc == 5) {
1522                 /* List of columns */
1523                 if ((cur = find_table(a->argv[4]))) {
1524                         struct columns *col;
1525                         ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
1526                         ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
1527                         AST_LIST_TRAVERSE(&cur->columns, col, list) {
1528                                 ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
1529                         }
1530                         release_table(cur);
1531                 } else {
1532                         ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
1533                 }
1534         }
1535         return 0;
1536 }
1537
1538 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1539 {
1540         char status[256], credentials[100] = "";
1541         int ctimesec = time(NULL) - connect_time;
1542
1543         switch (cmd) {
1544         case CLI_INIT:
1545                 e->command = "realtime show pgsql status";
1546                 e->usage =
1547                         "Usage: realtime show pgsql status\n"
1548                         "       Shows connection information for the PostgreSQL RealTime driver\n";
1549                 return NULL;
1550         case CLI_GENERATE:
1551                 return NULL;
1552         }
1553
1554         if (a->argc != 4)
1555                 return CLI_SHOWUSAGE;
1556
1557         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1558                 if (!ast_strlen_zero(dbhost))
1559                         snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
1560                 else if (!ast_strlen_zero(dbsock))
1561                         snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
1562                 else
1563                         snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
1564
1565                 if (!ast_strlen_zero(dbuser))
1566                         snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
1567
1568                 if (ctimesec > 31536000)
1569                         ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1570                                         status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
1571                                         (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1572                 else if (ctimesec > 86400)
1573                         ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
1574                                         credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
1575                                         ctimesec % 60);
1576                 else if (ctimesec > 3600)
1577                         ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
1578                                         ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1579                 else if (ctimesec > 60)
1580                         ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
1581                                         ctimesec % 60);
1582                 else
1583                         ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1584
1585                 return CLI_SUCCESS;
1586         } else {
1587                 return CLI_FAILURE;
1588         }
1589 }
1590
1591 /* needs usecount semantics defined */
1592 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL RealTime Configuration Driver",
1593                 .load = load_module,
1594                 .unload = unload_module,
1595                 .reload = reload
1596                );