use ast_*alloc and don't create duplicated error messages.
[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 #include <stdlib.h>
26 #include <string.h>
27 #include <libpq-fe.h>                   /* PostgreSQL */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include "asterisk/file.h"
34 #include "asterisk/logger.h"
35 #include "asterisk/channel.h"
36 #include "asterisk/pbx.h"
37 #include "asterisk/config.h"
38 #include "asterisk/module.h"
39 #include "asterisk/lock.h"
40 #include "asterisk/options.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/cli.h"
43
44 static char *res_config_pgsql_desc = "Postgresql RealTime Configuration Driver";
45
46 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
47
48 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
49
50 PGconn *pgsqlConn = NULL;
51
52 #define MAX_DB_OPTION_SIZE 64
53
54 static char dbhost[MAX_DB_OPTION_SIZE] = "";
55 static char dbuser[MAX_DB_OPTION_SIZE] = "";
56 static char dbpass[MAX_DB_OPTION_SIZE] = "";
57 static char dbname[MAX_DB_OPTION_SIZE] = "";
58 static char dbsock[MAX_DB_OPTION_SIZE] = "";
59 static int dbport = 5432;
60 static time_t connect_time = 0;
61
62 static int parse_config(void);
63 static int pgsql_reconnect(const char *database);
64 static int realtime_pgsql_status(int fd, int argc, char **argv);
65
66 LOCAL_USER_DECL;
67
68 static char cli_realtime_pgsql_status_usage[] =
69         "Usage: realtime pgsql status\n"
70         "       Shows connection information for the Postgresql RealTime driver\n";
71
72 static struct ast_cli_entry cli_realtime_pgsql_status = {
73          { "realtime", "pgsql", "status", NULL }, realtime_pgsql_status,
74          "Shows connection information for the Postgresql RealTime driver",
75          cli_realtime_pgsql_status_usage, NULL
76  };
77
78 static struct ast_variable *realtime_pgsql(const char *database, const char *table, va_list ap)
79 {
80         PGresult *result = NULL;
81         int num_rows = 0;
82         char sql[256];
83         char *stringp;
84         char *chunk;
85         char *op;
86         const char *newparam, *newval;
87         struct ast_variable *var = NULL, *prev = NULL;
88
89         if (!table) {
90                 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
91                 return NULL;
92         }
93
94         /* Get the first parameter and first value in our list of passed paramater/value pairs */
95         newparam = va_arg(ap, const char *);
96         newval = va_arg(ap, const char *);
97         if (!newparam || !newval) {
98                 ast_log(LOG_WARNING,
99                                 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
100                 if (pgsqlConn) {
101                         PQfinish(pgsqlConn);
102                         pgsqlConn = NULL;
103                 };
104                 return NULL;
105         }
106
107         /* Create the first part of the query using the first parameter/value pairs we just extracted
108            If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
109         op = strchr(newparam, ' ') ? "" : " =";
110
111         snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
112                          newval);
113         while ((newparam = va_arg(ap, const char *))) {
114                 newval = va_arg(ap, const char *);
115                 if (!strchr(newparam, ' '))
116                         op = " =";
117                 else
118                         op = "";
119                 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
120                                  op, newval);
121         }
122         va_end(ap);
123
124         /* We now have our complete statement; Lets connect to the server and execute it. */
125         ast_mutex_lock(&pgsql_lock);
126         if (!pgsql_reconnect(database)) {
127                 ast_mutex_unlock(&pgsql_lock);
128                 return NULL;
129         }
130
131         if (!(result = PQexec(pgsqlConn, sql))) {
132                 ast_log(LOG_WARNING,
133                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
134                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
135                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
136                                 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_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
147                         ast_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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_log(LOG_DEBUG, "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 (chunk && !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                 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 (initfield && (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_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
281                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
282                                 PQerrorMessage(pgsqlConn));
283                 ast_mutex_unlock(&pgsql_lock);
284                 return NULL;
285         } else {
286                 ExecStatusType result_status = PQresultStatus(result);
287                 if (result_status != PGRES_COMMAND_OK
288                         && result_status != PGRES_TUPLES_OK
289                         && result_status != PGRES_NONFATAL_ERROR) {
290                         ast_log(LOG_WARNING,
291                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
292                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
293                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
294                                         PQresultErrorMessage(result), PQresStatus(result_status));
295                         ast_mutex_unlock(&pgsql_lock);
296                         return NULL;
297                 }
298         }
299
300         ast_log(LOG_DEBUG, "2Postgresql RealTime: Result=%p Query: %s\n", result, sql);
301
302         if ((num_rows = PQntuples(result)) > 0) {
303                 int numFields = PQnfields(result);
304                 int i = 0;
305                 int rowIndex = 0;
306                 char **fieldnames = NULL;
307
308                 ast_log(LOG_DEBUG, "Postgresql RealTime: Found %d rows.\n", num_rows);
309
310                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
311                         ast_mutex_unlock(&pgsql_lock);
312                         PQclear(result);
313                         return NULL;
314                 }
315                 for (i = 0; i < numFields; i++)
316                         fieldnames[i] = PQfname(result, i);
317
318                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
319                         var = NULL;
320                         cat = ast_category_new("");
321                         if (!cat) {
322                                 ast_log(LOG_WARNING, "Out of memory!\n");
323                                 continue;
324                         }
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 {
444         PGresult *result = NULL;
445         long num_rows;
446         struct ast_variable *new_v;
447         struct ast_category *cur_cat = NULL;
448         char sql[250] = "";
449         char last[80] = "";
450         int last_cat_metric = 0;
451
452         last[0] = '\0';
453
454         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
455                 ast_log(LOG_WARNING, "Postgresql RealTime: Cannot configure myself.\n");
456                 return NULL;
457         }
458
459         snprintf(sql, sizeof(sql),
460                          "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",
461                          table, file);
462
463         ast_log(LOG_DEBUG, "Postgresql RealTime: Static SQL: %s\n", sql);
464
465         /* We now have our complete statement; Lets connect to the server and execute it. */
466         ast_mutex_lock(&pgsql_lock);
467         if (!pgsql_reconnect(database)) {
468                 ast_mutex_unlock(&pgsql_lock);
469                 return NULL;
470         }
471
472         if (!(result = PQexec(pgsqlConn, sql))) {
473                 ast_log(LOG_WARNING,
474                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
475                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
476                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
477                                 PQerrorMessage(pgsqlConn));
478                 ast_mutex_unlock(&pgsql_lock);
479                 return NULL;
480         } else {
481                 ExecStatusType result_status = PQresultStatus(result);
482                 if (result_status != PGRES_COMMAND_OK
483                         && result_status != PGRES_TUPLES_OK
484                         && result_status != PGRES_NONFATAL_ERROR) {
485                         ast_log(LOG_WARNING,
486                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
487                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
488                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
489                                         PQresultErrorMessage(result), PQresStatus(result_status));
490                         ast_mutex_unlock(&pgsql_lock);
491                         return NULL;
492                 }
493         }
494
495         if ((num_rows = PQntuples(result)) > 0) {
496                 int numFields = PQnfields(result);
497                 int i = 0;
498                 int rowIndex = 0;
499                 char **fieldnames = NULL;
500
501                 ast_log(LOG_DEBUG, "Postgresql RealTime: Found %ld rows.\n", num_rows);
502
503                 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
504                         ast_mutex_unlock(&pgsql_lock);
505                         PQclear(result);
506                         return NULL;
507                 }
508                 for (i = 0; i < numFields; i++)
509                         fieldnames[i] = PQfname(result, i);
510
511                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
512                         char *field_category = PQgetvalue(result, rowIndex, 0);
513                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
514                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
515                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
516                         if (!strcmp(field_var_name, "#include")) {
517                                 if (!ast_config_internal_load(field_var_val, cfg)) {
518                                         PQclear(result);
519                                         ast_mutex_unlock(&pgsql_lock);
520                                         return NULL;
521                                 }
522                                 continue;
523                         }
524
525                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
526                                 cur_cat = ast_category_new(field_category);
527                                 if (!cur_cat) {
528                                         ast_log(LOG_WARNING, "Out of memory!\n");
529                                         break;
530                                 }
531                                 strcpy(last, field_category);
532                                 last_cat_metric = atoi(field_cat_metric);
533                                 ast_category_append(cfg, cur_cat);
534                         }
535                         new_v = ast_variable_new(field_var_name, field_var_val);
536                         ast_variable_append(cur_cat, new_v);
537                 }
538         } else {
539                 ast_log(LOG_WARNING,
540                                 "Postgresql RealTime: Could not find config '%s' in database.\n", file);
541         }
542
543         PQclear(result);
544         ast_mutex_unlock(&pgsql_lock);
545
546         return cfg;
547 }
548
549 static struct ast_config_engine pgsql_engine = {
550         .name = "pgsql",
551         .load_func = config_pgsql,
552         .realtime_func = realtime_pgsql,
553         .realtime_multi_func = realtime_multi_pgsql,
554         .update_func = update_pgsql
555 };
556
557 int load_module(void)
558 {
559         parse_config();
560
561         ast_mutex_lock(&pgsql_lock);
562
563         if (!pgsql_reconnect(NULL)) {
564                 ast_log(LOG_WARNING,
565                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
566                 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
567                                 PQerrorMessage(pgsqlConn));
568         }
569
570         ast_config_engine_register(&pgsql_engine);
571         if (option_verbose) {
572                 ast_verbose("Postgresql RealTime driver loaded.\n");
573         }
574         ast_cli_register(&cli_realtime_pgsql_status);
575
576         ast_mutex_unlock(&pgsql_lock);
577
578         return 0;
579 }
580
581 int unload_module(void)
582 {
583         /* Aquire control before doing anything to the module itself. */
584         ast_mutex_lock(&pgsql_lock);
585
586         if (pgsqlConn) {
587                 PQfinish(pgsqlConn);
588                 pgsqlConn = NULL;
589         };
590         ast_cli_unregister(&cli_realtime_pgsql_status);
591         ast_config_engine_deregister(&pgsql_engine);
592         if (option_verbose) {
593                 ast_verbose("Postgresql RealTime unloaded.\n");
594         }
595
596         STANDARD_HANGUP_LOCALUSERS;
597
598         /* Unlock so something else can destroy the lock. */
599         ast_mutex_unlock(&pgsql_lock);
600
601         return 0;
602 }
603
604 int reload(void)
605 {
606         /* Aquire control before doing anything to the module itself. */
607         ast_mutex_lock(&pgsql_lock);
608
609         if (pgsqlConn) {
610                 PQfinish(pgsqlConn);
611                 pgsqlConn = NULL;
612         };
613         parse_config();
614
615         if (!pgsql_reconnect(NULL)) {
616                 ast_log(LOG_WARNING,
617                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
618                 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
619                                 PQerrorMessage(pgsqlConn));
620         }
621
622         ast_verbose(VERBOSE_PREFIX_2 "Postgresql RealTime reloaded.\n");
623
624         /* Done reloading. Release lock so others can now use driver. */
625         ast_mutex_unlock(&pgsql_lock);
626
627         return 0;
628 }
629
630 int parse_config(void)
631 {
632         struct ast_config *config;
633         char *s;
634
635         config = ast_config_load(RES_CONFIG_PGSQL_CONF);
636
637         if (config) {
638                 if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
639                         ast_log(LOG_WARNING,
640                                         "Postgresql RealTime: No database user found, using 'asterisk' as default.\n");
641                         strcpy(dbuser, "asterisk");
642                 } else {
643                         ast_copy_string(dbuser, s, sizeof(dbuser));
644                 }
645
646                 if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
647                         ast_log(LOG_WARNING,
648                                         "Postgresql RealTime: No database password found, using 'asterisk' as default.\n");
649                         strcpy(dbpass, "asterisk");
650                 } else {
651                         ast_copy_string(dbpass, s, sizeof(dbpass));
652                 }
653
654                 if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
655                         ast_log(LOG_WARNING,
656                                         "Postgresql RealTime: No database host found, using localhost via socket.\n");
657                         dbhost[0] = '\0';
658                 } else {
659                         ast_copy_string(dbhost, s, sizeof(dbhost));
660                 }
661
662                 if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
663                         ast_log(LOG_WARNING,
664                                         "Postgresql RealTime: No database name found, using 'asterisk' as default.\n");
665                         strcpy(dbname, "asterisk");
666                 } else {
667                         ast_copy_string(dbname, s, sizeof(dbname));
668                 }
669
670                 if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
671                         ast_log(LOG_WARNING,
672                                         "Postgresql RealTime: No database port found, using 5432 as default.\n");
673                         dbport = 5432;
674                 } else {
675                         dbport = atoi(s);
676                 }
677
678                 if (dbhost && !(s = ast_variable_retrieve(config, "general", "dbsock"))) {
679                         ast_log(LOG_WARNING,
680                                         "Postgresql RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
681                         strcpy(dbsock, "/tmp/pgsql.sock");
682                 } else {
683                         ast_copy_string(dbsock, s, sizeof(dbsock));
684                 }
685         }
686         ast_config_destroy(config);
687
688         if (dbhost) {
689                 ast_log(LOG_DEBUG, "Postgresql RealTime Host: %s\n", dbhost);
690                 ast_log(LOG_DEBUG, "Postgresql RealTime Port: %i\n", dbport);
691         } else {
692                 ast_log(LOG_DEBUG, "Postgresql RealTime Socket: %s\n", dbsock);
693         }
694         ast_log(LOG_DEBUG, "Postgresql RealTime User: %s\n", dbuser);
695         ast_log(LOG_DEBUG, "Postgresql RealTime Password: %s\n", dbpass);
696         ast_log(LOG_DEBUG, "Postgresql RealTime DBName: %s\n", dbname);
697
698         return 1;
699 }
700
701 const char *description(void)
702 {
703         return res_config_pgsql_desc;
704 }
705
706 int usecount(void)
707 {
708         /* Try and get a lock. If unsuccessful, than that means another thread is using the pgsql object. */
709         if (ast_mutex_trylock(&pgsql_lock)) {
710                 ast_log(LOG_DEBUG, "Postgresql RealTime: Module usage count is 1.\n");
711                 return 1;
712         }
713         ast_mutex_unlock(&pgsql_lock);
714         return 0;
715 }
716
717 const char *key()
718 {
719         return ASTERISK_GPL_KEY;
720 }
721
722 static int pgsql_reconnect(const char *database)
723 {
724         char my_database[50];
725
726         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
727
728         /* mutex lock should have been locked before calling this function. */
729
730         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
731                 PQfinish(pgsqlConn);
732                 pgsqlConn = NULL;
733         }
734
735         if ((!pgsqlConn) && (dbhost || dbsock) && dbuser && dbpass && my_database) {
736                 char *connInfo = NULL;
737                 unsigned int size = 100 + strlen(dbhost)
738                         + strlen(dbuser)
739                         + strlen(dbpass)
740                         + strlen(my_database);
741                 
742                 if (!(connInfo = ast_malloc(size)))
743                         return 0;
744                 
745                 sprintf(connInfo, "host=%s port=%d dbname=%s user=%s password=%s",
746                                         dbhost, dbport, my_database, dbuser, dbpass);
747                 ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
748                 pgsqlConn = PQconnectdb(connInfo);
749                 ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
750                 free(connInfo);
751                 connInfo = NULL;
752                 ast_log(LOG_DEBUG, "pgsqlConn=%p\n", pgsqlConn);
753                 if (pgsqlConn) {
754                         ast_log(LOG_DEBUG, "Postgresql RealTime: Successfully connected to database.\n");
755                         connect_time = time(NULL);
756                         return 1;
757                 } else {
758                         ast_log(LOG_ERROR,
759                                         "Postgresql RealTime: Failed to connect database server %s on %s. Check debug for more info.\n",
760                                         dbname, dbhost);
761                         ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
762                                         PQresultErrorMessage(NULL));
763                         return 0;
764                 }
765         } else {
766                 ast_log(LOG_DEBUG, "Postgresql RealTime: Everything is fine.\n");
767                 return 1;
768         }
769 }
770
771 static int realtime_pgsql_status(int fd, int argc, char **argv)
772 {
773         char status[256], status2[100] = "";
774         int ctime = time(NULL) - connect_time;
775
776         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
777                 if (dbhost) {
778                         snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
779                 } else if (dbsock) {
780                         snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
781                 } else {
782                         snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
783                 }
784
785                 if (dbuser && *dbuser) {
786                         snprintf(status2, 99, " with username %s", dbuser);
787                 }
788
789                 if (ctime > 31536000) {
790                         ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
791                                         status, status2, ctime / 31536000, (ctime % 31536000) / 86400,
792                                         (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
793                 } else if (ctime > 86400) {
794                         ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
795                                         status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60,
796                                         ctime % 60);
797                 } else if (ctime > 3600) {
798                         ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2,
799                                         ctime / 3600, (ctime % 3600) / 60, ctime % 60);
800                 } else if (ctime > 60) {
801                         ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60,
802                                         ctime % 60);
803                 } else {
804                         ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
805                 }
806
807                 return RESULT_SUCCESS;
808         } else {
809                 return RESULT_FAILURE;
810         }
811 }