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