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