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