Continuation of issue 9968 (revision 69081). This should be the last one.
[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 (!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                 ast_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 (!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                 ast_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 sqlbuf[1024] = "";
466         char *sql;
467         size_t sqlleft = sizeof(sqlbuf);
468         char last[80] = "";
469         int last_cat_metric = 0;
470
471         last[0] = '\0';
472
473         if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
474                 ast_log(LOG_WARNING, "Postgresql RealTime: Cannot configure myself.\n");
475                 return NULL;
476         }
477
478         ast_build_string(&sql, &sqlleft, "SELECT category, var_name, var_val, cat_metric FROM %s ", table);
479         ast_build_string(&sql, &sqlleft, "WHERE filename='%s' and commented=0", file);
480         ast_build_string(&sql, &sqlleft, "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ");
481
482         if (option_debug)
483                 ast_log(LOG_DEBUG, "Postgresql RealTime: Static SQL: %s\n", sqlbuf);
484
485         /* We now have our complete statement; Lets connect to the server and execute it. */
486         ast_mutex_lock(&pgsql_lock);
487         if (!pgsql_reconnect(database)) {
488                 ast_mutex_unlock(&pgsql_lock);
489                 return NULL;
490         }
491
492         if (!(result = PQexec(pgsqlConn, sqlbuf))) {
493                 ast_log(LOG_WARNING,
494                                 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
495                 if (option_debug) {
496                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
497                         ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
498                                         PQerrorMessage(pgsqlConn));
499                 }
500                 ast_mutex_unlock(&pgsql_lock);
501                 return NULL;
502         } else {
503                 ExecStatusType result_status = PQresultStatus(result);
504                 if (result_status != PGRES_COMMAND_OK
505                         && result_status != PGRES_TUPLES_OK
506                         && result_status != PGRES_NONFATAL_ERROR) {
507                         ast_log(LOG_WARNING,
508                                         "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
509                         if (option_debug) {
510                                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
511                                 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
512                                                 PQresultErrorMessage(result), PQresStatus(result_status));
513                         }
514                         ast_mutex_unlock(&pgsql_lock);
515                         return NULL;
516                 }
517         }
518
519         if ((num_rows = PQntuples(result)) > 0) {
520                 int rowIndex = 0;
521
522                 if (option_debug)
523                         ast_log(LOG_DEBUG, "Postgresql RealTime: Found %ld rows.\n", num_rows);
524
525                 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
526                         char *field_category = PQgetvalue(result, rowIndex, 0);
527                         char *field_var_name = PQgetvalue(result, rowIndex, 1);
528                         char *field_var_val = PQgetvalue(result, rowIndex, 2);
529                         char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
530                         if (!strcmp(field_var_name, "#include")) {
531                                 if (!ast_config_internal_load(field_var_val, cfg, 0)) {
532                                         PQclear(result);
533                                         ast_mutex_unlock(&pgsql_lock);
534                                         return NULL;
535                                 }
536                                 continue;
537                         }
538
539                         if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
540                                 cur_cat = ast_category_new(field_category);
541                                 if (!cur_cat)
542                                         break;
543                                 strcpy(last, field_category);
544                                 last_cat_metric = atoi(field_cat_metric);
545                                 ast_category_append(cfg, cur_cat);
546                         }
547                         new_v = ast_variable_new(field_var_name, field_var_val);
548                         ast_variable_append(cur_cat, new_v);
549                 }
550         } else {
551                 ast_log(LOG_WARNING,
552                                 "Postgresql RealTime: Could not find config '%s' in database.\n", file);
553         }
554
555         PQclear(result);
556         ast_mutex_unlock(&pgsql_lock);
557
558         return cfg;
559 }
560
561 static struct ast_config_engine pgsql_engine = {
562         .name = "pgsql",
563         .load_func = config_pgsql,
564         .realtime_func = realtime_pgsql,
565         .realtime_multi_func = realtime_multi_pgsql,
566         .update_func = update_pgsql
567 };
568
569 static int load_module(void)
570 {
571         if(!parse_config())
572                 return AST_MODULE_LOAD_DECLINE;
573
574         ast_mutex_lock(&pgsql_lock);
575
576         if (!pgsql_reconnect(NULL)) {
577                 ast_log(LOG_WARNING,
578                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
579                 if (option_debug)
580                         ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
581                                         PQerrorMessage(pgsqlConn));
582         }
583
584         ast_config_engine_register(&pgsql_engine);
585         if (option_verbose) {
586                 ast_verbose("Postgresql RealTime driver loaded.\n");
587         }
588         ast_cli_register_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
589
590         ast_mutex_unlock(&pgsql_lock);
591
592         return 0;
593 }
594
595 static int unload_module(void)
596 {
597         /* Aquire control before doing anything to the module itself. */
598         ast_mutex_lock(&pgsql_lock);
599
600         if (pgsqlConn) {
601                 PQfinish(pgsqlConn);
602                 pgsqlConn = NULL;
603         };
604         ast_cli_unregister_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
605         ast_config_engine_deregister(&pgsql_engine);
606         if (option_verbose) {
607                 ast_verbose("Postgresql RealTime unloaded.\n");
608         }
609
610         ast_module_user_hangup_all();
611
612         /* Unlock so something else can destroy the lock. */
613         ast_mutex_unlock(&pgsql_lock);
614
615         return 0;
616 }
617
618 static int reload(void)
619 {
620         /* Aquire control before doing anything to the module itself. */
621         ast_mutex_lock(&pgsql_lock);
622
623         if (pgsqlConn) {
624                 PQfinish(pgsqlConn);
625                 pgsqlConn = NULL;
626         };
627         parse_config();
628
629         if (!pgsql_reconnect(NULL)) {
630                 ast_log(LOG_WARNING,
631                                 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
632                 if (option_debug)
633                         ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
634                                         PQerrorMessage(pgsqlConn));
635         }
636
637         ast_verbose(VERBOSE_PREFIX_2 "Postgresql RealTime reloaded.\n");
638
639         /* Done reloading. Release lock so others can now use driver. */
640         ast_mutex_unlock(&pgsql_lock);
641
642         return 0;
643 }
644
645 static int parse_config(void)
646 {
647         struct ast_config *config;
648         const char *s;
649
650         config = ast_config_load(RES_CONFIG_PGSQL_CONF);
651
652         if (!config) {
653                 ast_log(LOG_WARNING, "Unable to load config %s\n",RES_CONFIG_PGSQL_CONF);
654                 return 0;
655         }
656         if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
657                 ast_log(LOG_WARNING,
658                                 "Postgresql RealTime: No database user found, using 'asterisk' as default.\n");
659                 strcpy(dbuser, "asterisk");
660         } else {
661                 ast_copy_string(dbuser, s, sizeof(dbuser));
662         }
663
664         if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
665                 ast_log(LOG_WARNING,
666                                 "Postgresql RealTime: No database password found, using 'asterisk' as default.\n");
667                 strcpy(dbpass, "asterisk");
668         } else {
669                 ast_copy_string(dbpass, s, sizeof(dbpass));
670         }
671
672         if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
673                 ast_log(LOG_WARNING,
674                                 "Postgresql RealTime: No database host found, using localhost via socket.\n");
675                 dbhost[0] = '\0';
676         } else {
677                 ast_copy_string(dbhost, s, sizeof(dbhost));
678         }
679
680         if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
681                 ast_log(LOG_WARNING,
682                                 "Postgresql RealTime: No database name found, using 'asterisk' as default.\n");
683                 strcpy(dbname, "asterisk");
684         } else {
685                 ast_copy_string(dbname, s, sizeof(dbname));
686         }
687
688         if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
689                 ast_log(LOG_WARNING,
690                                 "Postgresql RealTime: No database port found, using 5432 as default.\n");
691                 dbport = 5432;
692         } else {
693                 dbport = atoi(s);
694         }
695
696         if (dbhost && !(s = ast_variable_retrieve(config, "general", "dbsock"))) {
697                 ast_log(LOG_WARNING,
698                                 "Postgresql RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
699                 strcpy(dbsock, "/tmp/pgsql.sock");
700         } else {
701                 ast_copy_string(dbsock, s, sizeof(dbsock));
702         }
703         ast_config_destroy(config);
704
705         if (option_debug) {
706                 if (dbhost) {
707                         ast_log(LOG_DEBUG, "Postgresql RealTime Host: %s\n", dbhost);
708                         ast_log(LOG_DEBUG, "Postgresql RealTime Port: %i\n", dbport);
709                 } else {
710                         ast_log(LOG_DEBUG, "Postgresql RealTime Socket: %s\n", dbsock);
711                 }
712                 ast_log(LOG_DEBUG, "Postgresql RealTime User: %s\n", dbuser);
713                 ast_log(LOG_DEBUG, "Postgresql RealTime Password: %s\n", dbpass);
714                 ast_log(LOG_DEBUG, "Postgresql RealTime DBName: %s\n", dbname);
715         }
716
717         return 1;
718 }
719
720 static int pgsql_reconnect(const char *database)
721 {
722         char my_database[50];
723
724         ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
725
726         /* mutex lock should have been locked before calling this function. */
727
728         if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
729                 PQfinish(pgsqlConn);
730                 pgsqlConn = NULL;
731         }
732
733         if ((!pgsqlConn) && (dbhost || dbsock) && dbuser && dbpass && my_database) {
734                 char *connInfo = NULL;
735                 unsigned int size = 100 + strlen(dbhost)
736                         + strlen(dbuser)
737                         + strlen(dbpass)
738                         + strlen(my_database);
739                 
740                 if (!(connInfo = ast_malloc(size)))
741                         return 0;
742                 
743                 sprintf(connInfo, "host=%s port=%d dbname=%s user=%s password=%s",
744                                         dbhost, dbport, my_database, dbuser, dbpass);
745                 if (option_debug)
746                         ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
747                 pgsqlConn = PQconnectdb(connInfo);
748                 if (option_debug)
749                         ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
750                 ast_free(connInfo);
751                 connInfo = NULL;
752                 if (option_debug)
753                         ast_log(LOG_DEBUG, "pgsqlConn=%p\n", pgsqlConn);
754                 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
755                         if (option_debug)
756                                 ast_log(LOG_DEBUG, "Postgresql RealTime: Successfully connected to database.\n");
757                         connect_time = time(NULL);
758                         return 1;
759                 } else {
760                         ast_log(LOG_ERROR,
761                                         "Postgresql RealTime: Failed to connect database server %s on %s. Check debug for more info.\n",
762                                         dbname, dbhost);
763                         if (option_debug)
764                                 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
765                                                 PQresultErrorMessage(NULL));
766                         return 0;
767                 }
768         } else {
769                 if (option_debug)
770                         ast_log(LOG_DEBUG, "Postgresql RealTime: Everything is fine.\n");
771                 return 1;
772         }
773 }
774
775 static int realtime_pgsql_status(int fd, int argc, char **argv)
776 {
777         char status[256], status2[100] = "";
778         int ctime = time(NULL) - connect_time;
779
780         if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
781                 if (dbhost) {
782                         snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
783                 } else if (dbsock) {
784                         snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
785                 } else {
786                         snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
787                 }
788
789                 if (dbuser && *dbuser) {
790                         snprintf(status2, 99, " with username %s", dbuser);
791                 }
792
793                 if (ctime > 31536000) {
794                         ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
795                                         status, status2, ctime / 31536000, (ctime % 31536000) / 86400,
796                                         (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
797                 } else if (ctime > 86400) {
798                         ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
799                                         status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60,
800                                         ctime % 60);
801                 } else if (ctime > 3600) {
802                         ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2,
803                                         ctime / 3600, (ctime % 3600) / 60, ctime % 60);
804                 } else if (ctime > 60) {
805                         ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60,
806                                         ctime % 60);
807                 } else {
808                         ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
809                 }
810
811                 return RESULT_SUCCESS;
812         } else {
813                 return RESULT_FAILURE;
814         }
815 }
816
817 /* needs usecount semantics defined */
818 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PostgreSQL RealTime Configuration Driver",
819                 .load = load_module,
820                 .unload = unload_module,
821                 .reload = reload
822                );