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