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