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