It is no longer required for each module that deals with a channel to call ast_module...
[asterisk/asterisk.git] / res / res_config_pgsql.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Copyright (C) 1999-2005, Digium, Inc.
5  * 
6  * Manuel Guesdon <mguesdon@oxymium.net> - Postgresql RealTime Driver Author/Adaptor
7  * Mark Spencer <markster@digium.com>  - Asterisk Author
8  * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
9  *
10  * res_config_pgsql.c <Postgresql plugin for RealTime configuration engine>
11  *
12  * v1.0   - (07-11-05) - Initial version based on res_config_mysql v2.0
13  */
14
15 /*! \file
16  *
17  * \brief Postgresql plugin for Asterisk RealTime Architecture
18  *
19  * \author Mark Spencer <markster@digium.com>
20  * \author Manuel Guesdon <mguesdon@oxymium.net> - Postgresql RealTime Driver Author/Adaptor
21  *
22  * \arg http://www.postgresql.org
23  */
24
25 /*** MODULEINFO
26         <depend>pgsql</depend>
27  ***/
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <libpq-fe.h>                   /* PostgreSQL */
37
38 #include "asterisk/file.h"
39 #include "asterisk/logger.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/config.h"
43 #include "asterisk/module.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/options.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/cli.h"
48
49 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
50
51 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
52
53 PGconn *pgsqlConn = NULL;
54
55 #define MAX_DB_OPTION_SIZE 64
56
57 static char dbhost[MAX_DB_OPTION_SIZE] = "";
58 static char dbuser[MAX_DB_OPTION_SIZE] = "";
59 static char dbpass[MAX_DB_OPTION_SIZE] = "";
60 static char dbname[MAX_DB_OPTION_SIZE] = "";
61 static char dbsock[MAX_DB_OPTION_SIZE] = "";
62 static int dbport = 5432;
63 static time_t connect_time = 0;
64
65 static int parse_config(void);
66 static int pgsql_reconnect(const char *database);
67 static int realtime_pgsql_status(int fd, int argc, char **argv);
68
69 static const char cli_realtime_pgsql_status_usage[] =
70         "Usage: realtime pgsql status\n"
71         "       Shows connection information for the Postgresql RealTime driver\n";
72
73 static struct ast_cli_entry cli_realtime[] = {
74         { { "realtime", "pgsql", "status", NULL },
75         realtime_pgsql_status, "Shows connection information for the Postgresql RealTime driver",
76         cli_realtime_pgsql_status_usage },
77 };
78
79 static struct ast_variable *realtime_pgsql(const char *database, const char *table, va_list ap)
80 {
81         PGresult *result = NULL;
82         int num_rows = 0;
83         char sql[256];
84         char *stringp;
85         char *chunk;
86         char *op;
87         const char *newparam, *newval;
88         struct ast_variable *var = NULL, *prev = NULL;
89
90         if (!table) {
91                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
92                 return NULL;
93         }
94
95         /* Get the first parameter and first value in our list of passed paramater/value pairs */
96         newparam = va_arg(ap, const char *);
97         newval = va_arg(ap, const char *);
98         if (!newparam || !newval) {
99                 ast_log(LOG_WARNING,
100                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
101                 if (pgsqlConn) {
102                         PQfinish(pgsqlConn);
103                         pgsqlConn = NULL;
104                 };
105                 return NULL;
106         }
107
108         /* Create the first part of the query using the first parameter/value pairs we just extracted
109            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
110         op = strchr(newparam, ' ') ? "" : " =";
111
112         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
113                          newval);
114         while ((newparam = va_arg(ap, const char *))) {
115                 newval = va_arg(ap, const char *);
116                 if (!strchr(newparam, ' '))
117                         op = " =";
118                 else
119                         op = "";
120                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
121                                  op, newval);
122         }
123         va_end(ap);
124
125         /* We now have our complete statement; Lets connect to the server and execute it. */
126         ast_mutex_lock(&pgsql_lock);
127         if (!pgsql_reconnect(database)) {
128                 ast_mutex_unlock(&pgsql_lock);
129                 return NULL;
130         }
131
132         if (!(result = PQexec(pgsqlConn, sql))) {
133                 ast_log(LOG_WARNING,
134                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
135                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
136                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
137                 ast_mutex_unlock(&pgsql_lock);
138                 return NULL;
139         } else {
140                 ExecStatusType result_status = PQresultStatus(result);
141                 if (result_status != PGRES_COMMAND_OK
142                         && result_status != PGRES_TUPLES_OK
143                         && result_status != PGRES_NONFATAL_ERROR) {
144                         ast_log(LOG_WARNING,
145                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
146                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
147                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
148                                                 PQresultErrorMessage(result), PQresStatus(result_status));
149                         ast_mutex_unlock(&pgsql_lock);
150                         return NULL;
151                 }
152         }
153
154         ast_debug(1, "1Postgresql RealTime: Result=%p Query: %s\n", result, sql);
155
156         if ((num_rows = PQntuples(result)) > 0) {
157                 int i = 0;
158                 int rowIndex = 0;
159                 int numFields = PQnfields(result);
160                 char **fieldnames = NULL;
161
162                 ast_debug(1, "Postgresql RealTime: Found %d rows.\n", num_rows);
163
164                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
165                         ast_mutex_unlock(&pgsql_lock);
166                         PQclear(result);
167                         return NULL;
168                 }
169                 for (i = 0; i < numFields; i++)
170                         fieldnames[i] = PQfname(result, i);
171                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
172                         for (i = 0; i < numFields; i++) {
173                                 stringp = PQgetvalue(result, rowIndex, i);
174                                 while (stringp) {
175                                         chunk = strsep(&stringp, ";");
176                                         if (!ast_strlen_zero(ast_strip(chunk))) {
177                                                 if (prev) {
178                                                         prev->next = ast_variable_new(fieldnames[i], chunk);
179                                                         if (prev->next) {
180                                                                 prev = prev->next;
181                                                         }
182                                                 } else {
183                                                         prev = var = ast_variable_new(fieldnames[i], chunk);
184                                                 }
185                                         }
186                                 }
187                         }
188                 }
189                 ast_free(fieldnames);
190         } else {
191                 ast_log(LOG_WARNING,
192                                 "Postgresql RealTime: Could not find any rows in table %s.\n", table);
193         }
194
195         ast_mutex_unlock(&pgsql_lock);
196         PQclear(result);
197
198         return var;
199 }
200
201 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, va_list ap)
202 {
203         PGresult *result = NULL;
204         int num_rows = 0;
205         char sql[256];
206         const char *initfield = NULL;
207         char *stringp;
208         char *chunk;
209         char *op;
210         const char *newparam, *newval;
211         struct ast_variable *var = NULL;
212         struct ast_config *cfg = NULL;
213         struct ast_category *cat = NULL;
214
215         if (!table) {
216                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
217                 return NULL;
218         }
219
220         if (!(cfg = ast_config_new()))
221                 return NULL;
222
223         /* Get the first parameter and first value in our list of passed paramater/value pairs */
224         newparam = va_arg(ap, const char *);
225         newval = va_arg(ap, const char *);
226         if (!newparam || !newval) {
227                 ast_log(LOG_WARNING,
228                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
229                 if (pgsqlConn) {
230                         PQfinish(pgsqlConn);
231                         pgsqlConn = NULL;
232                 };
233                 return NULL;
234         }
235
236         initfield = ast_strdupa(newparam);
237         if ((op = strchr(initfield, ' '))) {
238                 *op = '\0';
239         }
240
241         /* Create the first part of the query using the first parameter/value pairs we just extracted
242            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
243
244         if (!strchr(newparam, ' '))
245                 op = " =";
246         else
247                 op = "";
248
249         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
250                          newval);
251         while ((newparam = va_arg(ap, const char *))) {
252                 newval = va_arg(ap, const char *);
253                 if (!strchr(newparam, ' '))
254                         op = " =";
255                 else
256                         op = "";
257                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
258                                  op, newval);
259         }
260
261         if (initfield) {
262                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " ORDER BY %s", initfield);
263         }
264
265         va_end(ap);
266
267         /* We now have our complete statement; Lets connect to the server and execute it. */
268         ast_mutex_lock(&pgsql_lock);
269         if (!pgsql_reconnect(database)) {
270                 ast_mutex_unlock(&pgsql_lock);
271                 return NULL;
272         }
273
274         if (!(result = PQexec(pgsqlConn, sql))) {
275                 ast_log(LOG_WARNING,
276                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
277                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
278                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
279                 ast_mutex_unlock(&pgsql_lock);
280                 return NULL;
281         } else {
282                 ExecStatusType result_status = PQresultStatus(result);
283                 if (result_status != PGRES_COMMAND_OK
284                         && result_status != PGRES_TUPLES_OK
285                         && result_status != PGRES_NONFATAL_ERROR) {
286                         ast_log(LOG_WARNING,
287                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
288                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
289                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
290                                                 PQresultErrorMessage(result), PQresStatus(result_status));
291                         ast_mutex_unlock(&pgsql_lock);
292                         return NULL;
293                 }
294         }
295
296         ast_debug(1, "2Postgresql RealTime: Result=%p Query: %s\n", result, sql);
297
298         if ((num_rows = PQntuples(result)) > 0) {
299                 int numFields = PQnfields(result);
300                 int i = 0;
301                 int rowIndex = 0;
302                 char **fieldnames = NULL;
303
304                 ast_debug(1, "Postgresql RealTime: Found %d rows.\n", num_rows);
305
306                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
307                         ast_mutex_unlock(&pgsql_lock);
308                         PQclear(result);
309                         return NULL;
310                 }
311                 for (i = 0; i < numFields; i++)
312                         fieldnames[i] = PQfname(result, i);
313
314                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
315                         var = NULL;
316                         if (!(cat = ast_category_new("")))
317                                 continue;
318                         for (i = 0; i < numFields; i++) {
319                                 stringp = PQgetvalue(result, rowIndex, i);
320                                 while (stringp) {
321                                         chunk = strsep(&stringp, ";");
322                                         if (!ast_strlen_zero(ast_strip(chunk))) {
323                                                 if (initfield && !strcmp(initfield, fieldnames[i])) {
324                                                         ast_category_rename(cat, chunk);
325                                                 }
326                                                 var = ast_variable_new(fieldnames[i], chunk);
327                                                 ast_variable_append(cat, var);
328                                         }
329                                 }
330                         }
331                         ast_category_append(cfg, cat);
332                 }
333                 ast_free(fieldnames);
334         } else {
335                 ast_log(LOG_WARNING,
336                                 "Postgresql RealTime: Could not find any rows in table %s.\n", table);
337         }
338
339         ast_mutex_unlock(&pgsql_lock);
340         PQclear(result);
341
342         return cfg;
343 }
344
345 static int update_pgsql(const char *database, const char *table, const char *keyfield,
346                                                 const char *lookup, va_list ap)
347 {
348         PGresult *result = NULL;
349         int numrows = 0;
350         char sql[256];
351         const char *newparam, *newval;
352
353         if (!table) {
354                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
355                 return -1;
356         }
357
358         /* Get the first parameter and first value in our list of passed paramater/value pairs */
359         newparam = va_arg(ap, const char *);
360         newval = va_arg(ap, const char *);
361         if (!newparam || !newval) {
362                 ast_log(LOG_WARNING,
363                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
364                 if (pgsqlConn) {
365                         PQfinish(pgsqlConn);
366                         pgsqlConn = NULL;
367                 };
368                 return -1;
369         }
370
371         /* Create the first part of the query using the first parameter/value pairs we just extracted
372            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
373
374         snprintf(sql, sizeof(sql), "UPDATE %s SET %s = '%s'", table, newparam, newval);
375         while ((newparam = va_arg(ap, const char *))) {
376                 newval = va_arg(ap, const char *);
377                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ", %s = '%s'", newparam,
378                                  newval);
379         }
380         va_end(ap);
381         snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " WHERE %s = '%s'", keyfield,
382                          lookup);
383
384         ast_debug(1, "Postgresql RealTime: Update SQL: %s\n", sql);
385
386         /* We now have our complete statement; Lets connect to the server and execute it. */
387         ast_mutex_lock(&pgsql_lock);
388         if (!pgsql_reconnect(database)) {
389                 ast_mutex_unlock(&pgsql_lock);
390                 return -1;
391         }
392
393         if (!(result = PQexec(pgsqlConn, sql))) {
394                 ast_log(LOG_WARNING,
395                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
396                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
397                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
398                 ast_mutex_unlock(&pgsql_lock);
399                 return -1;
400         } else {
401                 ExecStatusType result_status = PQresultStatus(result);
402                 if (result_status != PGRES_COMMAND_OK
403                         && result_status != PGRES_TUPLES_OK
404                         && result_status != PGRES_NONFATAL_ERROR) {
405                         ast_log(LOG_WARNING,
406                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
407                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
408                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
409                                                 PQresultErrorMessage(result), PQresStatus(result_status));
410                         ast_mutex_unlock(&pgsql_lock);
411                         return -1;
412                 }
413         }
414
415         numrows = atoi(PQcmdTuples(result));
416         ast_mutex_unlock(&pgsql_lock);
417
418         ast_debug(1, "Postgresql RealTime: Updated %d rows on table: %s\n", numrows, table);
419
420         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
421          * An integer greater than zero indicates the number of rows affected
422          * Zero indicates that no records were updated
423          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
424          */
425
426         if (numrows >= 0)
427                 return (int) numrows;
428
429         return -1;
430 }
431
432 static struct ast_config *config_pgsql(const char *database, const char *table,
433                                            const char *file, struct ast_config *cfg,
434                                            int withcomments)
435 {
436         PGresult *result = NULL;
437         long num_rows;
438         struct ast_variable *new_v;
439         struct ast_category *cur_cat = NULL;
440         char sqlbuf[1024] = "";
441         char *sql;
442         size_t sqlleft = sizeof(sqlbuf);
443         char last[80] = "";
444         int last_cat_metric = 0;
445
446         last[0] = '\0';
447
448         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
449                 ast_log(LOG_WARNING, "Postgresql RealTime: Cannot configure myself.\n");
450                 return NULL;
451         }
452
453         ast_build_string(&sql, &sqlleft, "SELECT category, var_name, var_val, cat_metric FROM %s ", table);
454         ast_build_string(&sql, &sqlleft, "WHERE filename='%s' and commented=0", file);
455         ast_build_string(&sql, &sqlleft, "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ");
456
457         ast_debug(1, "Postgresql RealTime: Static SQL: %s\n", sqlbuf);
458
459         /* We now have our complete statement; Lets connect to the server and execute it. */
460         ast_mutex_lock(&pgsql_lock);
461         if (!pgsql_reconnect(database)) {
462                 ast_mutex_unlock(&pgsql_lock);
463                 return NULL;
464         }
465
466         if (!(result = PQexec(pgsqlConn, sqlbuf))) {
467                 ast_log(LOG_WARNING,
468                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
469                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
470                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
471                 ast_mutex_unlock(&pgsql_lock);
472                 return NULL;
473         } else {
474                 ExecStatusType result_status = PQresultStatus(result);
475                 if (result_status != PGRES_COMMAND_OK
476                         && result_status != PGRES_TUPLES_OK
477                         && result_status != PGRES_NONFATAL_ERROR) {
478                         ast_log(LOG_WARNING,
479                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
480                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
481                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
482                                                 PQresultErrorMessage(result), PQresStatus(result_status));
483                         ast_mutex_unlock(&pgsql_lock);
484                         return NULL;
485                 }
486         }
487
488         if ((num_rows = PQntuples(result)) > 0) {
489                 int rowIndex = 0;
490
491                 ast_debug(1, "Postgresql RealTime: Found %ld rows.\n", num_rows);
492
493                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
494                         char *field_category = PQgetvalue(result, rowIndex, 0);
495                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
496                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
497                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
498                         if (!strcmp(field_var_name, "#include")) {
499                                 if (!ast_config_internal_load(field_var_val, cfg, 0)) {
500                                         PQclear(result);
501                                         ast_mutex_unlock(&pgsql_lock);
502                                         return NULL;
503                                 }
504                                 continue;
505                         }
506
507                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
508                                 cur_cat = ast_category_new(field_category);
509                                 if (!cur_cat)
510                                         break;
511                                 strcpy(last, field_category);
512                                 last_cat_metric = atoi(field_cat_metric);
513                                 ast_category_append(cfg, cur_cat);
514                         }
515                         new_v = ast_variable_new(field_var_name, field_var_val);
516                         ast_variable_append(cur_cat, new_v);
517                 }
518         } else {
519                 ast_log(LOG_WARNING,
520                                 "Postgresql RealTime: Could not find config '%s' in database.\n", file);
521         }
522
523         PQclear(result);
524         ast_mutex_unlock(&pgsql_lock);
525
526         return cfg;
527 }
528
529 static struct ast_config_engine pgsql_engine = {
530         .name = "pgsql",
531         .load_func = config_pgsql,
532         .realtime_func = realtime_pgsql,
533         .realtime_multi_func = realtime_multi_pgsql,
534         .update_func = update_pgsql
535 };
536
537 static int load_module(void)
538 {
539         if(!parse_config())
540                 return AST_MODULE_LOAD_DECLINE;
541
542         ast_mutex_lock(&pgsql_lock);
543
544         if (!pgsql_reconnect(NULL)) {
545                 ast_log(LOG_WARNING,
546                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
547                 ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
548         }
549
550         ast_config_engine_register(&pgsql_engine);
551         if (option_verbose) {
552                 ast_verbose("Postgresql RealTime driver loaded.\n");
553         }
554         ast_cli_register_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
555
556         ast_mutex_unlock(&pgsql_lock);
557
558         return 0;
559 }
560
561 static int unload_module(void)
562 {
563         /* Aquire control before doing anything to the module itself. */
564         ast_mutex_lock(&pgsql_lock);
565
566         if (pgsqlConn) {
567                 PQfinish(pgsqlConn);
568                 pgsqlConn = NULL;
569         };
570         ast_cli_unregister_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
571         ast_config_engine_deregister(&pgsql_engine);
572         if (option_verbose) {
573                 ast_verbose("Postgresql RealTime unloaded.\n");
574         }
575
576         /* Unlock so something else can destroy the lock. */
577         ast_mutex_unlock(&pgsql_lock);
578
579         return 0;
580 }
581
582 static int reload(void)
583 {
584         /* Aquire control before doing anything to the module itself. */
585         ast_mutex_lock(&pgsql_lock);
586
587         if (pgsqlConn) {
588                 PQfinish(pgsqlConn);
589                 pgsqlConn = NULL;
590         };
591         parse_config();
592
593         if (!pgsql_reconnect(NULL)) {
594                 ast_log(LOG_WARNING,
595                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
596                 ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
597         }
598
599         ast_verbose(VERBOSE_PREFIX_2 "Postgresql RealTime reloaded.\n");
600
601         /* Done reloading. Release lock so others can now use driver. */
602         ast_mutex_unlock(&pgsql_lock);
603
604         return 0;
605 }
606
607 static int parse_config(void)
608 {
609         struct ast_config *config;
610         const char *s;
611
612         config = ast_config_load(RES_CONFIG_PGSQL_CONF);
613
614         if (!config) {
615                 ast_log(LOG_WARNING, "Unable to load config %s\n",RES_CONFIG_PGSQL_CONF);
616                 return 0;
617         }
618         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
619                 ast_log(LOG_WARNING,
620                                 "Postgresql RealTime: No database user found, using 'asterisk' as default.\n");
621                 strcpy(dbuser, "asterisk");
622         } else {
623                 ast_copy_string(dbuser, s, sizeof(dbuser));
624         }
625
626         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
627                 ast_log(LOG_WARNING,
628                                 "Postgresql RealTime: No database password found, using 'asterisk' as default.\n");
629                 strcpy(dbpass, "asterisk");
630         } else {
631                 ast_copy_string(dbpass, s, sizeof(dbpass));
632         }
633
634         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
635                 ast_log(LOG_WARNING,
636                                 "Postgresql RealTime: No database host found, using localhost via socket.\n");
637                 dbhost[0] = '\0';
638         } else {
639                 ast_copy_string(dbhost, s, sizeof(dbhost));
640         }
641
642         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
643                 ast_log(LOG_WARNING,
644                                 "Postgresql RealTime: No database name found, using 'asterisk' as default.\n");
645                 strcpy(dbname, "asterisk");
646         } else {
647                 ast_copy_string(dbname, s, sizeof(dbname));
648         }
649
650         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
651                 ast_log(LOG_WARNING,
652                                 "Postgresql RealTime: No database port found, using 5432 as default.\n");
653                 dbport = 5432;
654         } else {
655                 dbport = atoi(s);
656         }
657
658         if (dbhost && !(s = ast_variable_retrieve(config, "general", "dbsock"))) {
659                 ast_log(LOG_WARNING,
660                                 "Postgresql RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
661                 strcpy(dbsock, "/tmp/pgsql.sock");
662         } else {
663                 ast_copy_string(dbsock, s, sizeof(dbsock));
664         }
665         ast_config_destroy(config);
666
667         if (option_debug) {
668                 if (dbhost) {
669                         ast_debug(1, "Postgresql RealTime Host: %s\n", dbhost);
670                         ast_debug(1, "Postgresql RealTime Port: %i\n", dbport);
671                 } else {
672                         ast_debug(1, "Postgresql RealTime Socket: %s\n", dbsock);
673                 }
674                 ast_debug(1, "Postgresql RealTime User: %s\n", dbuser);
675                 ast_debug(1, "Postgresql RealTime Password: %s\n", dbpass);
676                 ast_debug(1, "Postgresql RealTime DBName: %s\n", dbname);
677         }
678
679         return 1;
680 }
681
682 static int pgsql_reconnect(const char *database)
683 {
684         char my_database[50];
685
686         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
687
688         /* mutex lock should have been locked before calling this function. */
689
690         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
691                 PQfinish(pgsqlConn);
692                 pgsqlConn = NULL;
693         }
694
695         if ((!pgsqlConn) && (dbhost || dbsock) && dbuser && dbpass && my_database) {
696                 char *connInfo = NULL;
697                 unsigned int size = 100 + strlen(dbhost)
698                         + strlen(dbuser)
699                         + strlen(dbpass)
700                         + strlen(my_database);
701                 
702                 if (!(connInfo = ast_malloc(size)))
703                         return 0;
704                 
705                 sprintf(connInfo, "host=%s port=%d dbname=%s user=%s password=%s",
706                                         dbhost, dbport, my_database, dbuser, dbpass);
707                 ast_debug(1, "%u connInfo=%s\n", size, connInfo);
708                 pgsqlConn = PQconnectdb(connInfo);
709                 ast_debug(1, "%u connInfo=%s\n", size, connInfo);
710                 ast_free(connInfo);
711                 connInfo = NULL;
712                 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
713                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
714                         ast_debug(1, "Postgresql RealTime: Successfully connected to database.\n");
715                         connect_time = time(NULL);
716                         return 1;
717                 } else {
718                         ast_log(LOG_ERROR,
719                                         "Postgresql RealTime: Failed to connect database server %s on %s. Check debug for more info.\n",
720                                         dbname, dbhost);
721                         ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQresultErrorMessage(NULL));
722                         return 0;
723                 }
724         } else {
725                 ast_debug(1, "Postgresql RealTime: Everything is fine.\n");
726                 return 1;
727         }
728 }
729
730 static int realtime_pgsql_status(int fd, int argc, char **argv)
731 {
732         char status[256], status2[100] = "";
733         int ctime = time(NULL) - connect_time;
734
735         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
736                 if (dbhost) {
737                         snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
738                 } else if (dbsock) {
739                         snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
740                 } else {
741                         snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
742                 }
743
744                 if (dbuser && *dbuser) {
745                         snprintf(status2, 99, " with username %s", dbuser);
746                 }
747
748                 if (ctime > 31536000) {
749                         ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
750                                         status, status2, ctime / 31536000, (ctime % 31536000) / 86400,
751                                         (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
752                 } else if (ctime > 86400) {
753                         ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
754                                         status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60,
755                                         ctime % 60);
756                 } else if (ctime > 3600) {
757                         ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2,
758                                         ctime / 3600, (ctime % 3600) / 60, ctime % 60);
759                 } else if (ctime > 60) {
760                         ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60,
761                                         ctime % 60);
762                 } else {
763                         ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
764                 }
765
766                 return RESULT_SUCCESS;
767         } else {
768                 return RESULT_FAILURE;
769         }
770 }
771
772 /* needs usecount semantics defined */
773 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PostgreSQL RealTime Configuration Driver",
774                 .load = load_module,
775                 .unload = unload_module,
776                 .reload = reload
777                );