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