Add a massive set of changes for converting to use the ast_debug() macro.
[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_realloca ra;
212         struct ast_variable *var = NULL;
213         struct ast_config *cfg = NULL;
214         struct ast_category *cat = NULL;
215
216         if (!table) {
217                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
218                 return NULL;
219         }
220
221         memset(&ra, 0, sizeof(ra));
222
223         if (!(cfg = ast_config_new()))
224                 return NULL;
225
226         /* Get the first parameter and first value in our list of passed paramater/value pairs */
227         newparam = va_arg(ap, const char *);
228         newval = va_arg(ap, const char *);
229         if (!newparam || !newval) {
230                 ast_log(LOG_WARNING,
231                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
232                 if (pgsqlConn) {
233                         PQfinish(pgsqlConn);
234                         pgsqlConn = NULL;
235                 };
236                 return NULL;
237         }
238
239         initfield = ast_strdupa(newparam);
240         if ((op = strchr(initfield, ' '))) {
241                 *op = '\0';
242         }
243
244         /* Create the first part of the query using the first parameter/value pairs we just extracted
245            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
246
247         if (!strchr(newparam, ' '))
248                 op = " =";
249         else
250                 op = "";
251
252         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
253                          newval);
254         while ((newparam = va_arg(ap, const char *))) {
255                 newval = va_arg(ap, const char *);
256                 if (!strchr(newparam, ' '))
257                         op = " =";
258                 else
259                         op = "";
260                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
261                                  op, newval);
262         }
263
264         if (initfield) {
265                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " ORDER BY %s", initfield);
266         }
267
268         va_end(ap);
269
270         /* We now have our complete statement; Lets connect to the server and execute it. */
271         ast_mutex_lock(&pgsql_lock);
272         if (!pgsql_reconnect(database)) {
273                 ast_mutex_unlock(&pgsql_lock);
274                 return NULL;
275         }
276
277         if (!(result = PQexec(pgsqlConn, sql))) {
278                 ast_log(LOG_WARNING,
279                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
280                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
281                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
282                 ast_mutex_unlock(&pgsql_lock);
283                 return NULL;
284         } else {
285                 ExecStatusType result_status = PQresultStatus(result);
286                 if (result_status != PGRES_COMMAND_OK
287                         && result_status != PGRES_TUPLES_OK
288                         && result_status != PGRES_NONFATAL_ERROR) {
289                         ast_log(LOG_WARNING,
290                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
291                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
292                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
293                                                 PQresultErrorMessage(result), PQresStatus(result_status));
294                         ast_mutex_unlock(&pgsql_lock);
295                         return NULL;
296                 }
297         }
298
299         ast_debug(1, "2Postgresql RealTime: Result=%p Query: %s\n", result, sql);
300
301         if ((num_rows = PQntuples(result)) > 0) {
302                 int numFields = PQnfields(result);
303                 int i = 0;
304                 int rowIndex = 0;
305                 char **fieldnames = NULL;
306
307                 ast_debug(1, "Postgresql RealTime: Found %d rows.\n", num_rows);
308
309                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
310                         ast_mutex_unlock(&pgsql_lock);
311                         PQclear(result);
312                         return NULL;
313                 }
314                 for (i = 0; i < numFields; i++)
315                         fieldnames[i] = PQfname(result, i);
316
317                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
318                         var = NULL;
319                         if (!(cat = ast_category_new("")))
320                                 continue;
321                         for (i = 0; i < numFields; i++) {
322                                 stringp = PQgetvalue(result, rowIndex, i);
323                                 while (stringp) {
324                                         chunk = strsep(&stringp, ";");
325                                         if (!ast_strlen_zero(ast_strip(chunk))) {
326                                                 if (initfield && !strcmp(initfield, fieldnames[i])) {
327                                                         ast_category_rename(cat, chunk);
328                                                 }
329                                                 var = ast_variable_new(fieldnames[i], chunk);
330                                                 ast_variable_append(cat, var);
331                                         }
332                                 }
333                         }
334                         ast_category_append(cfg, cat);
335                 }
336                 ast_free(fieldnames);
337         } else {
338                 ast_log(LOG_WARNING,
339                                 "Postgresql RealTime: Could not find any rows in table %s.\n", table);
340         }
341
342         ast_mutex_unlock(&pgsql_lock);
343         PQclear(result);
344
345         return cfg;
346 }
347
348 static int update_pgsql(const char *database, const char *table, const char *keyfield,
349                                                 const char *lookup, va_list ap)
350 {
351         PGresult *result = NULL;
352         int numrows = 0;
353         char sql[256];
354         const char *newparam, *newval;
355
356         if (!table) {
357                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
358                 return -1;
359         }
360
361         /* Get the first parameter and first value in our list of passed paramater/value pairs */
362         newparam = va_arg(ap, const char *);
363         newval = va_arg(ap, const char *);
364         if (!newparam || !newval) {
365                 ast_log(LOG_WARNING,
366                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
367                 if (pgsqlConn) {
368                         PQfinish(pgsqlConn);
369                         pgsqlConn = NULL;
370                 };
371                 return -1;
372         }
373
374         /* Create the first part of the query using the first parameter/value pairs we just extracted
375            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
376
377         snprintf(sql, sizeof(sql), "UPDATE %s SET %s = '%s'", table, newparam, newval);
378         while ((newparam = va_arg(ap, const char *))) {
379                 newval = va_arg(ap, const char *);
380                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ", %s = '%s'", newparam,
381                                  newval);
382         }
383         va_end(ap);
384         snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " WHERE %s = '%s'", keyfield,
385                          lookup);
386
387         ast_debug(1, "Postgresql RealTime: Update SQL: %s\n", sql);
388
389         /* We now have our complete statement; Lets connect to the server and execute it. */
390         ast_mutex_lock(&pgsql_lock);
391         if (!pgsql_reconnect(database)) {
392                 ast_mutex_unlock(&pgsql_lock);
393                 return -1;
394         }
395
396         if (!(result = PQexec(pgsqlConn, sql))) {
397                 ast_log(LOG_WARNING,
398                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
399                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
400                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
401                 ast_mutex_unlock(&pgsql_lock);
402                 return -1;
403         } else {
404                 ExecStatusType result_status = PQresultStatus(result);
405                 if (result_status != PGRES_COMMAND_OK
406                         && result_status != PGRES_TUPLES_OK
407                         && result_status != PGRES_NONFATAL_ERROR) {
408                         ast_log(LOG_WARNING,
409                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
410                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
411                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
412                                                 PQresultErrorMessage(result), PQresStatus(result_status));
413                         ast_mutex_unlock(&pgsql_lock);
414                         return -1;
415                 }
416         }
417
418         numrows = atoi(PQcmdTuples(result));
419         ast_mutex_unlock(&pgsql_lock);
420
421         ast_debug(1, "Postgresql RealTime: Updated %d rows on table: %s\n", numrows, table);
422
423         /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
424          * An integer greater than zero indicates the number of rows affected
425          * Zero indicates that no records were updated
426          * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
427          */
428
429         if (numrows >= 0)
430                 return (int) numrows;
431
432         return -1;
433 }
434
435 static struct ast_config *config_pgsql(const char *database, const char *table,
436                                            const char *file, struct ast_config *cfg,
437                                            int withcomments)
438 {
439         PGresult *result = NULL;
440         long num_rows;
441         struct ast_variable *new_v;
442         struct ast_category *cur_cat = NULL;
443         char sqlbuf[1024] = "";
444         char *sql;
445         size_t sqlleft = sizeof(sqlbuf);
446         char last[80] = "";
447         int last_cat_metric = 0;
448
449         last[0] = '\0';
450
451         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
452                 ast_log(LOG_WARNING, "Postgresql RealTime: Cannot configure myself.\n");
453                 return NULL;
454         }
455
456         ast_build_string(&sql, &sqlleft, "SELECT category, var_name, var_val, cat_metric FROM %s ", table);
457         ast_build_string(&sql, &sqlleft, "WHERE filename='%s' and commented=0", file);
458         ast_build_string(&sql, &sqlleft, "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ");
459
460         ast_debug(1, "Postgresql RealTime: Static SQL: %s\n", sqlbuf);
461
462         /* We now have our complete statement; Lets connect to the server and execute it. */
463         ast_mutex_lock(&pgsql_lock);
464         if (!pgsql_reconnect(database)) {
465                 ast_mutex_unlock(&pgsql_lock);
466                 return NULL;
467         }
468
469         if (!(result = PQexec(pgsqlConn, sqlbuf))) {
470                 ast_log(LOG_WARNING,
471                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
472                 ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
473                 ast_debug(1, "Postgresql RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
474                 ast_mutex_unlock(&pgsql_lock);
475                 return NULL;
476         } else {
477                 ExecStatusType result_status = PQresultStatus(result);
478                 if (result_status != PGRES_COMMAND_OK
479                         && result_status != PGRES_TUPLES_OK
480                         && result_status != PGRES_NONFATAL_ERROR) {
481                         ast_log(LOG_WARNING,
482                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
483                         ast_debug(1, "Postgresql RealTime: Query: %s\n", sql);
484                         ast_debug(1, "Postgresql RealTime: Query Failed because: %s (%s)\n",
485                                                 PQresultErrorMessage(result), PQresStatus(result_status));
486                         ast_mutex_unlock(&pgsql_lock);
487                         return NULL;
488                 }
489         }
490
491         if ((num_rows = PQntuples(result)) > 0) {
492                 int rowIndex = 0;
493
494                 ast_debug(1, "Postgresql RealTime: Found %ld rows.\n", num_rows);
495
496                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
497                         char *field_category = PQgetvalue(result, rowIndex, 0);
498                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
499                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
500                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
501                         if (!strcmp(field_var_name, "#include")) {
502                                 if (!ast_config_internal_load(field_var_val, cfg, 0)) {
503                                         PQclear(result);
504                                         ast_mutex_unlock(&pgsql_lock);
505                                         return NULL;
506                                 }
507                                 continue;
508                         }
509
510                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
511                                 cur_cat = ast_category_new(field_category);
512                                 if (!cur_cat)
513                                         break;
514                                 strcpy(last, field_category);
515                                 last_cat_metric = atoi(field_cat_metric);
516                                 ast_category_append(cfg, cur_cat);
517                         }
518                         new_v = ast_variable_new(field_var_name, field_var_val);
519                         ast_variable_append(cur_cat, new_v);
520                 }
521         } else {
522                 ast_log(LOG_WARNING,
523                                 "Postgresql RealTime: Could not find config '%s' in database.\n", file);
524         }
525
526         PQclear(result);
527         ast_mutex_unlock(&pgsql_lock);
528
529         return cfg;
530 }
531
532 static struct ast_config_engine pgsql_engine = {
533         .name = "pgsql",
534         .load_func = config_pgsql,
535         .realtime_func = realtime_pgsql,
536         .realtime_multi_func = realtime_multi_pgsql,
537         .update_func = update_pgsql
538 };
539
540 static int load_module(void)
541 {
542         if(!parse_config())
543                 return AST_MODULE_LOAD_DECLINE;
544
545         ast_mutex_lock(&pgsql_lock);
546
547         if (!pgsql_reconnect(NULL)) {
548                 ast_log(LOG_WARNING,
549                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
550                 ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
551         }
552
553         ast_config_engine_register(&pgsql_engine);
554         if (option_verbose) {
555                 ast_verbose("Postgresql RealTime driver loaded.\n");
556         }
557         ast_cli_register_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
558
559         ast_mutex_unlock(&pgsql_lock);
560
561         return 0;
562 }
563
564 static int unload_module(void)
565 {
566         /* Aquire control before doing anything to the module itself. */
567         ast_mutex_lock(&pgsql_lock);
568
569         if (pgsqlConn) {
570                 PQfinish(pgsqlConn);
571                 pgsqlConn = NULL;
572         };
573         ast_cli_unregister_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
574         ast_config_engine_deregister(&pgsql_engine);
575         if (option_verbose) {
576                 ast_verbose("Postgresql RealTime unloaded.\n");
577         }
578
579         ast_module_user_hangup_all();
580
581         /* Unlock so something else can destroy the lock. */
582         ast_mutex_unlock(&pgsql_lock);
583
584         return 0;
585 }
586
587 static int reload(void)
588 {
589         /* Aquire control before doing anything to the module itself. */
590         ast_mutex_lock(&pgsql_lock);
591
592         if (pgsqlConn) {
593                 PQfinish(pgsqlConn);
594                 pgsqlConn = NULL;
595         };
596         parse_config();
597
598         if (!pgsql_reconnect(NULL)) {
599                 ast_log(LOG_WARNING,
600                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
601                 ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
602         }
603
604         ast_verbose(VERBOSE_PREFIX_2 "Postgresql RealTime reloaded.\n");
605
606         /* Done reloading. Release lock so others can now use driver. */
607         ast_mutex_unlock(&pgsql_lock);
608
609         return 0;
610 }
611
612 static int parse_config(void)
613 {
614         struct ast_config *config;
615         const char *s;
616
617         config = ast_config_load(RES_CONFIG_PGSQL_CONF);
618
619         if (!config) {
620                 ast_log(LOG_WARNING, "Unable to load config %s\n",RES_CONFIG_PGSQL_CONF);
621                 return 0;
622         }
623         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
624                 ast_log(LOG_WARNING,
625                                 "Postgresql RealTime: No database user found, using 'asterisk' as default.\n");
626                 strcpy(dbuser, "asterisk");
627         } else {
628                 ast_copy_string(dbuser, s, sizeof(dbuser));
629         }
630
631         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
632                 ast_log(LOG_WARNING,
633                                 "Postgresql RealTime: No database password found, using 'asterisk' as default.\n");
634                 strcpy(dbpass, "asterisk");
635         } else {
636                 ast_copy_string(dbpass, s, sizeof(dbpass));
637         }
638
639         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
640                 ast_log(LOG_WARNING,
641                                 "Postgresql RealTime: No database host found, using localhost via socket.\n");
642                 dbhost[0] = '\0';
643         } else {
644                 ast_copy_string(dbhost, s, sizeof(dbhost));
645         }
646
647         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
648                 ast_log(LOG_WARNING,
649                                 "Postgresql RealTime: No database name found, using 'asterisk' as default.\n");
650                 strcpy(dbname, "asterisk");
651         } else {
652                 ast_copy_string(dbname, s, sizeof(dbname));
653         }
654
655         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
656                 ast_log(LOG_WARNING,
657                                 "Postgresql RealTime: No database port found, using 5432 as default.\n");
658                 dbport = 5432;
659         } else {
660                 dbport = atoi(s);
661         }
662
663         if (dbhost && !(s = ast_variable_retrieve(config, "general", "dbsock"))) {
664                 ast_log(LOG_WARNING,
665                                 "Postgresql RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
666                 strcpy(dbsock, "/tmp/pgsql.sock");
667         } else {
668                 ast_copy_string(dbsock, s, sizeof(dbsock));
669         }
670         ast_config_destroy(config);
671
672         if (option_debug) {
673                 if (dbhost) {
674                         ast_debug(1, "Postgresql RealTime Host: %s\n", dbhost);
675                         ast_debug(1, "Postgresql RealTime Port: %i\n", dbport);
676                 } else {
677                         ast_debug(1, "Postgresql RealTime Socket: %s\n", dbsock);
678                 }
679                 ast_debug(1, "Postgresql RealTime User: %s\n", dbuser);
680                 ast_debug(1, "Postgresql RealTime Password: %s\n", dbpass);
681                 ast_debug(1, "Postgresql RealTime DBName: %s\n", dbname);
682         }
683
684         return 1;
685 }
686
687 static int pgsql_reconnect(const char *database)
688 {
689         char my_database[50];
690
691         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
692
693         /* mutex lock should have been locked before calling this function. */
694
695         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
696                 PQfinish(pgsqlConn);
697                 pgsqlConn = NULL;
698         }
699
700         if ((!pgsqlConn) && (dbhost || dbsock) && dbuser && dbpass && my_database) {
701                 char *connInfo = NULL;
702                 unsigned int size = 100 + strlen(dbhost)
703                         + strlen(dbuser)
704                         + strlen(dbpass)
705                         + strlen(my_database);
706                 
707                 if (!(connInfo = ast_malloc(size)))
708                         return 0;
709                 
710                 sprintf(connInfo, "host=%s port=%d dbname=%s user=%s password=%s",
711                                         dbhost, dbport, my_database, dbuser, dbpass);
712                 ast_debug(1, "%u connInfo=%s\n", size, connInfo);
713                 pgsqlConn = PQconnectdb(connInfo);
714                 ast_debug(1, "%u connInfo=%s\n", size, connInfo);
715                 ast_free(connInfo);
716                 connInfo = NULL;
717                 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
718                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
719                         ast_debug(1, "Postgresql RealTime: Successfully connected to database.\n");
720                         connect_time = time(NULL);
721                         return 1;
722                 } else {
723                         ast_log(LOG_ERROR,
724                                         "Postgresql RealTime: Failed to connect database server %s on %s. Check debug for more info.\n",
725                                         dbname, dbhost);
726                         ast_debug(1, "Postgresql RealTime: Cannot Connect: %s\n", PQresultErrorMessage(NULL));
727                         return 0;
728                 }
729         } else {
730                 ast_debug(1, "Postgresql RealTime: Everything is fine.\n");
731                 return 1;
732         }
733 }
734
735 static int realtime_pgsql_status(int fd, int argc, char **argv)
736 {
737         char status[256], status2[100] = "";
738         int ctime = time(NULL) - connect_time;
739
740         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
741                 if (dbhost) {
742                         snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
743                 } else if (dbsock) {
744                         snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
745                 } else {
746                         snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
747                 }
748
749                 if (dbuser && *dbuser) {
750                         snprintf(status2, 99, " with username %s", dbuser);
751                 }
752
753                 if (ctime > 31536000) {
754                         ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
755                                         status, status2, ctime / 31536000, (ctime % 31536000) / 86400,
756                                         (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
757                 } else if (ctime > 86400) {
758                         ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
759                                         status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60,
760                                         ctime % 60);
761                 } else if (ctime > 3600) {
762                         ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2,
763                                         ctime / 3600, (ctime % 3600) / 60, ctime % 60);
764                 } else if (ctime > 60) {
765                         ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60,
766                                         ctime % 60);
767                 } else {
768                         ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
769                 }
770
771                 return RESULT_SUCCESS;
772         } else {
773                 return RESULT_FAILURE;
774         }
775 }
776
777 /* needs usecount semantics defined */
778 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PostgreSQL RealTime Configuration Driver",
779                 .load = load_module,
780                 .unload = unload_module,
781                 .reload = reload
782                );