Mon Apr 28 2014 10:05:46

Asterisk developer's documentation


res_config_pgsql.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Copyright (C) 1999-2010, Digium, Inc.
00005  *
00006  * Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
00007  * Mark Spencer <markster@digium.com>  - Asterisk Author
00008  * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
00009  *
00010  * res_config_pgsql.c <PostgreSQL plugin for RealTime configuration engine>
00011  *
00012  * v1.0   - (07-11-05) - Initial version based on res_config_mysql v2.0
00013  */
00014 
00015 /*! \file
00016  *
00017  * \brief PostgreSQL plugin for Asterisk RealTime Architecture
00018  *
00019  * \author Mark Spencer <markster@digium.com>
00020  * \author Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
00021  *
00022  * \extref PostgreSQL http://www.postgresql.org
00023  */
00024 
00025 /*** MODULEINFO
00026    <depend>pgsql</depend>
00027    <support_level>extended</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 407873 $")
00033 
00034 #include <libpq-fe.h>         /* PostgreSQL */
00035 
00036 #include "asterisk/file.h"
00037 #include "asterisk/channel.h"
00038 #include "asterisk/pbx.h"
00039 #include "asterisk/config.h"
00040 #include "asterisk/module.h"
00041 #include "asterisk/lock.h"
00042 #include "asterisk/utils.h"
00043 #include "asterisk/cli.h"
00044 
00045 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
00046 AST_THREADSTORAGE(sql_buf);
00047 AST_THREADSTORAGE(findtable_buf);
00048 AST_THREADSTORAGE(where_buf);
00049 AST_THREADSTORAGE(escapebuf_buf);
00050 AST_THREADSTORAGE(semibuf_buf);
00051 
00052 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
00053 
00054 static PGconn *pgsqlConn = NULL;
00055 static int version;
00056 #define has_schema_support (version > 70300 ? 1 : 0)
00057 
00058 #define MAX_DB_OPTION_SIZE 64
00059 
00060 struct columns {
00061    char *name;
00062    char *type;
00063    int len;
00064    unsigned int notnull:1;
00065    unsigned int hasdefault:1;
00066    AST_LIST_ENTRY(columns) list;
00067 };
00068 
00069 struct tables {
00070    ast_rwlock_t lock;
00071    AST_LIST_HEAD_NOLOCK(psql_columns, columns) columns;
00072    AST_LIST_ENTRY(tables) list;
00073    char name[0];
00074 };
00075 
00076 static AST_LIST_HEAD_STATIC(psql_tables, tables);
00077 
00078 static char dbhost[MAX_DB_OPTION_SIZE] = "";
00079 static char dbuser[MAX_DB_OPTION_SIZE] = "";
00080 static char dbpass[MAX_DB_OPTION_SIZE] = "";
00081 static char dbname[MAX_DB_OPTION_SIZE] = "";
00082 static char dbsock[MAX_DB_OPTION_SIZE] = "";
00083 static int dbport = 5432;
00084 static time_t connect_time = 0;
00085 
00086 static int parse_config(int reload);
00087 static int pgsql_reconnect(const char *database);
00088 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
00089 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
00090 
00091 static enum { RQ_WARN, RQ_CREATECLOSE, RQ_CREATECHAR } requirements;
00092 
00093 static struct ast_cli_entry cli_realtime[] = {
00094    AST_CLI_DEFINE(handle_cli_realtime_pgsql_status, "Shows connection information for the PostgreSQL RealTime driver"),
00095    AST_CLI_DEFINE(handle_cli_realtime_pgsql_cache, "Shows cached tables within the PostgreSQL realtime driver"),
00096 };
00097 
00098 #define ESCAPE_STRING(buffer, stringname) \
00099    do { \
00100       int len = strlen(stringname); \
00101       struct ast_str *semi = ast_str_thread_get(&semibuf_buf, len * 3 + 1); \
00102       const char *chunk = stringname; \
00103       ast_str_reset(semi); \
00104       for (; *chunk; chunk++) { \
00105          if (strchr(";^", *chunk)) { \
00106             ast_str_append(&semi, 0, "^%02hhX", *chunk); \
00107          } else { \
00108             ast_str_append(&semi, 0, "%c", *chunk); \
00109          } \
00110       } \
00111       if (ast_str_strlen(semi) > (ast_str_size(buffer) - 1) / 2) { \
00112          ast_str_make_space(&buffer, ast_str_strlen(semi) * 2 + 1); \
00113       } \
00114       PQescapeStringConn(pgsqlConn, ast_str_buffer(buffer), ast_str_buffer(semi), ast_str_size(buffer), &pgresult); \
00115    } while (0)
00116 
00117 static void destroy_table(struct tables *table)
00118 {
00119    struct columns *column;
00120    ast_rwlock_wrlock(&table->lock);
00121    while ((column = AST_LIST_REMOVE_HEAD(&table->columns, list))) {
00122       ast_free(column);
00123    }
00124    ast_rwlock_unlock(&table->lock);
00125    ast_rwlock_destroy(&table->lock);
00126    ast_free(table);
00127 }
00128 
00129 static struct tables *find_table(const char *database, const char *orig_tablename)
00130 {
00131    struct columns *column;
00132    struct tables *table;
00133    struct ast_str *sql = ast_str_thread_get(&findtable_buf, 330);
00134    char *pgerror;
00135    RAII_VAR(PGresult *, result, NULL, PQclear);
00136    char *fname, *ftype, *flen, *fnotnull, *fdef;
00137    int i, rows;
00138 
00139    AST_LIST_LOCK(&psql_tables);
00140    AST_LIST_TRAVERSE(&psql_tables, table, list) {
00141       if (!strcasecmp(table->name, orig_tablename)) {
00142          ast_debug(1, "Found table in cache; now locking\n");
00143          ast_rwlock_rdlock(&table->lock);
00144          ast_debug(1, "Lock cached table; now returning\n");
00145          AST_LIST_UNLOCK(&psql_tables);
00146          return table;
00147       }
00148    }
00149 
00150    ast_debug(1, "Table '%s' not found in cache, querying now\n", orig_tablename);
00151 
00152    /* Not found, scan the table */
00153    if (has_schema_support) {
00154       char *schemaname, *tablename;
00155       if (strchr(orig_tablename, '.')) {
00156          schemaname = ast_strdupa(orig_tablename);
00157          tablename = strchr(schemaname, '.');
00158          *tablename++ = '\0';
00159       } else {
00160          schemaname = "";
00161          tablename = ast_strdupa(orig_tablename);
00162       }
00163 
00164       /* Escape special characters in schemaname */
00165       if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
00166          char *tmp = schemaname, *ptr;
00167 
00168          ptr = schemaname = ast_alloca(strlen(tmp) * 2 + 1);
00169          for (; *tmp; tmp++) {
00170             if (strchr("\\'", *tmp)) {
00171                *ptr++ = *tmp;
00172             }
00173             *ptr++ = *tmp;
00174          }
00175          *ptr = '\0';
00176       }
00177       /* Escape special characters in tablename */
00178       if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
00179          char *tmp = tablename, *ptr;
00180 
00181          ptr = tablename = ast_alloca(strlen(tmp) * 2 + 1);
00182          for (; *tmp; tmp++) {
00183             if (strchr("\\'", *tmp)) {
00184                *ptr++ = *tmp;
00185             }
00186             *ptr++ = *tmp;
00187          }
00188          *ptr = '\0';
00189       }
00190 
00191       ast_str_set(&sql, 0, "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND c.relname = '%s' AND n.nspname = %s%s%s) INNER JOIN pg_catalog.pg_attribute a ON (NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum ORDER BY n.nspname, c.relname, attnum",
00192          tablename,
00193          ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
00194    } else {
00195       /* Escape special characters in tablename */
00196       if (strchr(orig_tablename, '\\') || strchr(orig_tablename, '\'')) {
00197          const char *tmp = orig_tablename;
00198          char *ptr;
00199 
00200          orig_tablename = ptr = ast_alloca(strlen(tmp) * 2 + 1);
00201          for (; *tmp; tmp++) {
00202             if (strchr("\\'", *tmp)) {
00203                *ptr++ = *tmp;
00204             }
00205             *ptr++ = *tmp;
00206          }
00207          *ptr = '\0';
00208       }
00209 
00210       ast_str_set(&sql, 0, "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM pg_class c, pg_type t, pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", orig_tablename);
00211    }
00212 
00213    ast_mutex_lock(&pgsql_lock);
00214    if (!pgsql_reconnect(database)) {
00215       AST_LIST_UNLOCK(&psql_tables);
00216       ast_mutex_unlock(&pgsql_lock);
00217       return NULL;
00218    }
00219 
00220    result = PQexec(pgsqlConn, ast_str_buffer(sql));
00221    ast_debug(1, "Query of table structure complete.  Now retrieving results.\n");
00222    if (PQresultStatus(result) != PGRES_TUPLES_OK) {
00223       pgerror = PQresultErrorMessage(result);
00224       ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
00225       AST_LIST_UNLOCK(&psql_tables);
00226       ast_mutex_unlock(&pgsql_lock);
00227       return NULL;
00228    }
00229 
00230    if (!(table = ast_calloc(1, sizeof(*table) + strlen(orig_tablename) + 1))) {
00231       ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
00232       AST_LIST_UNLOCK(&psql_tables);
00233       ast_mutex_unlock(&pgsql_lock);
00234       return NULL;
00235    }
00236    strcpy(table->name, orig_tablename); /* SAFE */
00237    ast_rwlock_init(&table->lock);
00238    AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
00239 
00240    rows = PQntuples(result);
00241    for (i = 0; i < rows; i++) {
00242       fname = PQgetvalue(result, i, 0);
00243       ftype = PQgetvalue(result, i, 1);
00244       flen = PQgetvalue(result, i, 2);
00245       fnotnull = PQgetvalue(result, i, 3);
00246       fdef = PQgetvalue(result, i, 4);
00247       ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
00248 
00249       if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + 2))) {
00250          ast_log(LOG_ERROR, "Unable to allocate column element for %s, %s\n", orig_tablename, fname);
00251          destroy_table(table);
00252          AST_LIST_UNLOCK(&psql_tables);
00253          ast_mutex_unlock(&pgsql_lock);
00254          return NULL;
00255       }
00256 
00257       if (strcmp(flen, "-1") == 0) {
00258          /* Some types, like chars, have the length stored in a different field */
00259          flen = PQgetvalue(result, i, 5);
00260          sscanf(flen, "%30d", &column->len);
00261          column->len -= 4;
00262       } else {
00263          sscanf(flen, "%30d", &column->len);
00264       }
00265       column->name = (char *)column + sizeof(*column);
00266       column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
00267       strcpy(column->name, fname);
00268       strcpy(column->type, ftype);
00269       if (*fnotnull == 't') {
00270          column->notnull = 1;
00271       } else {
00272          column->notnull = 0;
00273       }
00274       if (!ast_strlen_zero(fdef)) {
00275          column->hasdefault = 1;
00276       } else {
00277          column->hasdefault = 0;
00278       }
00279       AST_LIST_INSERT_TAIL(&table->columns, column, list);
00280    }
00281 
00282    AST_LIST_INSERT_TAIL(&psql_tables, table, list);
00283    ast_rwlock_rdlock(&table->lock);
00284    AST_LIST_UNLOCK(&psql_tables);
00285    ast_mutex_unlock(&pgsql_lock);
00286    return table;
00287 }
00288 
00289 #define release_table(table) ast_rwlock_unlock(&(table)->lock);
00290 
00291 static struct columns *find_column(struct tables *t, const char *colname)
00292 {
00293    struct columns *column;
00294 
00295    /* Check that the column exists in the table */
00296    AST_LIST_TRAVERSE(&t->columns, column, list) {
00297       if (strcmp(column->name, colname) == 0) {
00298          return column;
00299       }
00300    }
00301    return NULL;
00302 }
00303 
00304 static struct ast_variable *realtime_pgsql(const char *database, const char *tablename, va_list ap)
00305 {
00306    RAII_VAR(PGresult *, result, NULL, PQclear);
00307    int num_rows = 0, pgresult;
00308    struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
00309    struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
00310    char *stringp;
00311    char *chunk;
00312    char *op;
00313    const char *newparam, *newval;
00314    struct ast_variable *var = NULL, *prev = NULL;
00315 
00316    /*
00317     * Ignore database from the extconfig.conf since it was
00318     * configured by res_pgsql.conf.
00319     */
00320    database = dbname;
00321 
00322    if (!tablename) {
00323       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00324       return NULL;
00325    }
00326 
00327    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00328    newparam = va_arg(ap, const char *);
00329    newval = va_arg(ap, const char *);
00330    if (!newparam || !newval) {
00331       ast_log(LOG_WARNING,
00332             "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00333       if (pgsqlConn) {
00334          PQfinish(pgsqlConn);
00335          pgsqlConn = NULL;
00336       }
00337       return NULL;
00338    }
00339 
00340    /* Create the first part of the query using the first parameter/value pairs we just extracted
00341       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00342    op = strchr(newparam, ' ') ? "" : " =";
00343 
00344    ESCAPE_STRING(escapebuf, newval);
00345    if (pgresult) {
00346       ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00347       return NULL;
00348    }
00349 
00350    ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", tablename, newparam, op, ast_str_buffer(escapebuf));
00351    while ((newparam = va_arg(ap, const char *))) {
00352       newval = va_arg(ap, const char *);
00353       if (!strchr(newparam, ' '))
00354          op = " =";
00355       else
00356          op = "";
00357 
00358       ESCAPE_STRING(escapebuf, newval);
00359       if (pgresult) {
00360          ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00361          return NULL;
00362       }
00363 
00364       ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
00365    }
00366 
00367    /* We now have our complete statement; Lets connect to the server and execute it. */
00368    ast_mutex_lock(&pgsql_lock);
00369    if (!pgsql_reconnect(database)) {
00370       ast_mutex_unlock(&pgsql_lock);
00371       return NULL;
00372    }
00373 
00374    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
00375       ast_log(LOG_WARNING,
00376             "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", tablename, database);
00377       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00378       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
00379       ast_mutex_unlock(&pgsql_lock);
00380       return NULL;
00381    } else {
00382       ExecStatusType result_status = PQresultStatus(result);
00383       if (result_status != PGRES_COMMAND_OK
00384          && result_status != PGRES_TUPLES_OK
00385          && result_status != PGRES_NONFATAL_ERROR) {
00386          ast_log(LOG_WARNING,
00387                "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", tablename, database);
00388          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00389          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
00390                   PQresultErrorMessage(result), PQresStatus(result_status));
00391          ast_mutex_unlock(&pgsql_lock);
00392          return NULL;
00393       }
00394    }
00395 
00396    ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
00397 
00398    if ((num_rows = PQntuples(result)) > 0) {
00399       int i = 0;
00400       int rowIndex = 0;
00401       int numFields = PQnfields(result);
00402       char **fieldnames = NULL;
00403 
00404       ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
00405 
00406       if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
00407          ast_mutex_unlock(&pgsql_lock);
00408          return NULL;
00409       }
00410       for (i = 0; i < numFields; i++)
00411          fieldnames[i] = PQfname(result, i);
00412       for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
00413          for (i = 0; i < numFields; i++) {
00414             stringp = PQgetvalue(result, rowIndex, i);
00415             while (stringp) {
00416                chunk = strsep(&stringp, ";");
00417                if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
00418                   if (prev) {
00419                      prev->next = ast_variable_new(fieldnames[i], chunk, "");
00420                      if (prev->next) {
00421                         prev = prev->next;
00422                      }
00423                   } else {
00424                      prev = var = ast_variable_new(fieldnames[i], chunk, "");
00425                   }
00426                }
00427             }
00428          }
00429       }
00430       ast_free(fieldnames);
00431    } else {
00432       ast_debug(1, "Postgresql RealTime: Could not find any rows in table %s@%s.\n", tablename, database);
00433    }
00434 
00435    ast_mutex_unlock(&pgsql_lock);
00436 
00437    return var;
00438 }
00439 
00440 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, va_list ap)
00441 {
00442    RAII_VAR(PGresult *, result, NULL, PQclear);
00443    int num_rows = 0, pgresult;
00444    struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
00445    struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
00446    const char *initfield = NULL;
00447    char *stringp;
00448    char *chunk;
00449    char *op;
00450    const char *newparam, *newval;
00451    struct ast_variable *var = NULL;
00452    struct ast_config *cfg = NULL;
00453    struct ast_category *cat = NULL;
00454 
00455    /*
00456     * Ignore database from the extconfig.conf since it was
00457     * configured by res_pgsql.conf.
00458     */
00459    database = dbname;
00460 
00461    if (!table) {
00462       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00463       return NULL;
00464    }
00465 
00466    if (!(cfg = ast_config_new()))
00467       return NULL;
00468 
00469    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00470    newparam = va_arg(ap, const char *);
00471    newval = va_arg(ap, const char *);
00472    if (!newparam || !newval) {
00473       ast_log(LOG_WARNING,
00474             "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00475       if (pgsqlConn) {
00476          PQfinish(pgsqlConn);
00477          pgsqlConn = NULL;
00478       }
00479       ast_config_destroy(cfg);
00480       return NULL;
00481    }
00482 
00483    initfield = ast_strdupa(newparam);
00484    if ((op = strchr(initfield, ' '))) {
00485       *op = '\0';
00486    }
00487 
00488    /* Create the first part of the query using the first parameter/value pairs we just extracted
00489       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00490 
00491    if (!strchr(newparam, ' '))
00492       op = " =";
00493    else
00494       op = "";
00495 
00496    ESCAPE_STRING(escapebuf, newval);
00497    if (pgresult) {
00498       ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00499       ast_config_destroy(cfg);
00500       return NULL;
00501    }
00502 
00503    ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, ast_str_buffer(escapebuf));
00504    while ((newparam = va_arg(ap, const char *))) {
00505       newval = va_arg(ap, const char *);
00506       if (!strchr(newparam, ' '))
00507          op = " =";
00508       else
00509          op = "";
00510 
00511       ESCAPE_STRING(escapebuf, newval);
00512       if (pgresult) {
00513          ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00514          ast_config_destroy(cfg);
00515          return NULL;
00516       }
00517 
00518       ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
00519    }
00520 
00521    if (initfield) {
00522       ast_str_append(&sql, 0, " ORDER BY %s", initfield);
00523    }
00524 
00525 
00526    /* We now have our complete statement; Lets connect to the server and execute it. */
00527    ast_mutex_lock(&pgsql_lock);
00528    if (!pgsql_reconnect(database)) {
00529       ast_mutex_unlock(&pgsql_lock);
00530       ast_config_destroy(cfg);
00531       return NULL;
00532    }
00533 
00534    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
00535       ast_log(LOG_WARNING,
00536             "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
00537       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00538       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
00539       ast_mutex_unlock(&pgsql_lock);
00540       ast_config_destroy(cfg);
00541       return NULL;
00542    } else {
00543       ExecStatusType result_status = PQresultStatus(result);
00544       if (result_status != PGRES_COMMAND_OK
00545          && result_status != PGRES_TUPLES_OK
00546          && result_status != PGRES_NONFATAL_ERROR) {
00547          ast_log(LOG_WARNING,
00548                "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
00549          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00550          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
00551                   PQresultErrorMessage(result), PQresStatus(result_status));
00552          ast_mutex_unlock(&pgsql_lock);
00553          ast_config_destroy(cfg);
00554          return NULL;
00555       }
00556    }
00557 
00558    ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
00559 
00560    if ((num_rows = PQntuples(result)) > 0) {
00561       int numFields = PQnfields(result);
00562       int i = 0;
00563       int rowIndex = 0;
00564       char **fieldnames = NULL;
00565 
00566       ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
00567 
00568       if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
00569          ast_mutex_unlock(&pgsql_lock);
00570          ast_config_destroy(cfg);
00571          return NULL;
00572       }
00573       for (i = 0; i < numFields; i++)
00574          fieldnames[i] = PQfname(result, i);
00575 
00576       for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
00577          var = NULL;
00578          if (!(cat = ast_category_new("","",99999)))
00579             continue;
00580          for (i = 0; i < numFields; i++) {
00581             stringp = PQgetvalue(result, rowIndex, i);
00582             while (stringp) {
00583                chunk = strsep(&stringp, ";");
00584                if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
00585                   if (initfield && !strcmp(initfield, fieldnames[i])) {
00586                      ast_category_rename(cat, chunk);
00587                   }
00588                   var = ast_variable_new(fieldnames[i], chunk, "");
00589                   ast_variable_append(cat, var);
00590                }
00591             }
00592          }
00593          ast_category_append(cfg, cat);
00594       }
00595       ast_free(fieldnames);
00596    } else {
00597       ast_debug(1, "PostgreSQL RealTime: Could not find any rows in table %s.\n", table);
00598    }
00599 
00600    ast_mutex_unlock(&pgsql_lock);
00601 
00602    return cfg;
00603 }
00604 
00605 static int update_pgsql(const char *database, const char *tablename, const char *keyfield,
00606                   const char *lookup, va_list ap)
00607 {
00608    RAII_VAR(PGresult *, result, NULL, PQclear);
00609    int numrows = 0, pgresult;
00610    const char *newparam, *newval;
00611    struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
00612    struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
00613    struct tables *table;
00614    struct columns *column = NULL;
00615 
00616    /*
00617     * Ignore database from the extconfig.conf since it was
00618     * configured by res_pgsql.conf.
00619     */
00620    database = dbname;
00621 
00622    if (!tablename) {
00623       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00624       return -1;
00625    }
00626 
00627    if (!(table = find_table(database, tablename))) {
00628       ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
00629       return -1;
00630    }
00631 
00632    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00633    newparam = va_arg(ap, const char *);
00634    newval = va_arg(ap, const char *);
00635    if (!newparam || !newval) {
00636       ast_log(LOG_WARNING,
00637             "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00638       if (pgsqlConn) {
00639          PQfinish(pgsqlConn);
00640          pgsqlConn = NULL;
00641       }
00642       release_table(table);
00643       return -1;
00644    }
00645 
00646    /* Check that the column exists in the table */
00647    AST_LIST_TRAVERSE(&table->columns, column, list) {
00648       if (strcmp(column->name, newparam) == 0) {
00649          break;
00650       }
00651    }
00652 
00653    if (!column) {
00654       ast_log(LOG_ERROR, "PostgreSQL RealTime: Updating on column '%s', but that column does not exist within the table '%s'!\n", newparam, tablename);
00655       release_table(table);
00656       return -1;
00657    }
00658 
00659    /* Create the first part of the query using the first parameter/value pairs we just extracted
00660       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00661 
00662    ESCAPE_STRING(escapebuf, newval);
00663    if (pgresult) {
00664       ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00665       release_table(table);
00666       return -1;
00667    }
00668    ast_str_set(&sql, 0, "UPDATE %s SET %s = '%s'", tablename, newparam, ast_str_buffer(escapebuf));
00669 
00670    while ((newparam = va_arg(ap, const char *))) {
00671       newval = va_arg(ap, const char *);
00672 
00673       if (!find_column(table, newparam)) {
00674          ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s', but column does not exist!\n", newparam, tablename);
00675          continue;
00676       }
00677 
00678       ESCAPE_STRING(escapebuf, newval);
00679       if (pgresult) {
00680          ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00681          release_table(table);
00682          return -1;
00683       }
00684 
00685       ast_str_append(&sql, 0, ", %s = '%s'", newparam, ast_str_buffer(escapebuf));
00686    }
00687    release_table(table);
00688 
00689    ESCAPE_STRING(escapebuf, lookup);
00690    if (pgresult) {
00691       ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", lookup);
00692       return -1;
00693    }
00694 
00695    ast_str_append(&sql, 0, " WHERE %s = '%s'", keyfield, ast_str_buffer(escapebuf));
00696 
00697    ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
00698 
00699    /* We now have our complete statement; Lets connect to the server and execute it. */
00700    ast_mutex_lock(&pgsql_lock);
00701    if (!pgsql_reconnect(database)) {
00702       ast_mutex_unlock(&pgsql_lock);
00703       return -1;
00704    }
00705 
00706    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
00707       ast_log(LOG_WARNING,
00708             "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00709       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00710       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
00711       ast_mutex_unlock(&pgsql_lock);
00712       return -1;
00713    } else {
00714       ExecStatusType result_status = PQresultStatus(result);
00715       if (result_status != PGRES_COMMAND_OK
00716          && result_status != PGRES_TUPLES_OK
00717          && result_status != PGRES_NONFATAL_ERROR) {
00718          ast_log(LOG_WARNING,
00719                "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00720          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00721          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
00722                   PQresultErrorMessage(result), PQresStatus(result_status));
00723          ast_mutex_unlock(&pgsql_lock);
00724          return -1;
00725       }
00726    }
00727 
00728    numrows = atoi(PQcmdTuples(result));
00729    ast_mutex_unlock(&pgsql_lock);
00730 
00731    ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
00732 
00733    /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
00734     * An integer greater than zero indicates the number of rows affected
00735     * Zero indicates that no records were updated
00736     * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
00737     */
00738 
00739    if (numrows >= 0)
00740       return (int) numrows;
00741 
00742    return -1;
00743 }
00744 
00745 static int update2_pgsql(const char *database, const char *tablename, va_list ap)
00746 {
00747    RAII_VAR(PGresult *, result, NULL, PQclear);
00748    int numrows = 0, pgresult, first = 1;
00749    struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
00750    const char *newparam, *newval;
00751    struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
00752    struct ast_str *where = ast_str_thread_get(&where_buf, 100);
00753    struct tables *table;
00754 
00755    /*
00756     * Ignore database from the extconfig.conf since it was
00757     * configured by res_pgsql.conf.
00758     */
00759    database = dbname;
00760 
00761    if (!tablename) {
00762       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00763       return -1;
00764    }
00765 
00766    if (!escapebuf || !sql || !where) {
00767       /* Memory error, already handled */
00768       return -1;
00769    }
00770 
00771    if (!(table = find_table(database, tablename))) {
00772       ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
00773       return -1;
00774    }
00775 
00776    ast_str_set(&sql, 0, "UPDATE %s SET", tablename);
00777    ast_str_set(&where, 0, " WHERE");
00778 
00779    while ((newparam = va_arg(ap, const char *))) {
00780       if (!find_column(table, newparam)) {
00781          ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", newparam, tablename, database);
00782          release_table(table);
00783          return -1;
00784       }
00785 
00786       newval = va_arg(ap, const char *);
00787       ESCAPE_STRING(escapebuf, newval);
00788       if (pgresult) {
00789          ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00790          release_table(table);
00791          return -1;
00792       }
00793       ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", newparam, ast_str_buffer(escapebuf));
00794       first = 0;
00795    }
00796 
00797    if (first) {
00798       ast_log(LOG_WARNING,
00799             "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
00800       if (pgsqlConn) {
00801          PQfinish(pgsqlConn);
00802          pgsqlConn = NULL;
00803       }
00804       release_table(table);
00805       return -1;
00806    }
00807 
00808    /* Now retrieve the columns to update */
00809    first = 1;
00810    while ((newparam = va_arg(ap, const char *))) {
00811       newval = va_arg(ap, const char *);
00812 
00813       /* If the column is not within the table, then skip it */
00814       if (!find_column(table, newparam)) {
00815          ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", newparam, tablename, database);
00816          continue;
00817       }
00818 
00819       ESCAPE_STRING(escapebuf, newval);
00820       if (pgresult) {
00821          ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
00822          release_table(table);
00823          return -1;
00824       }
00825 
00826       ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", newparam, ast_str_buffer(escapebuf));
00827       first = 0;
00828    }
00829    release_table(table);
00830 
00831    ast_str_append(&sql, 0, "%s", ast_str_buffer(where));
00832 
00833    ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
00834 
00835    /* We now have our complete statement; connect to the server and execute it. */
00836    ast_mutex_lock(&pgsql_lock);
00837    if (!pgsql_reconnect(database)) {
00838       ast_mutex_unlock(&pgsql_lock);
00839       return -1;
00840    }
00841 
00842    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
00843       ast_log(LOG_WARNING,
00844             "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00845       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00846       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
00847       ast_mutex_unlock(&pgsql_lock);
00848       return -1;
00849    } else {
00850       ExecStatusType result_status = PQresultStatus(result);
00851       if (result_status != PGRES_COMMAND_OK
00852          && result_status != PGRES_TUPLES_OK
00853          && result_status != PGRES_NONFATAL_ERROR) {
00854          ast_log(LOG_WARNING,
00855                "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00856          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
00857          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
00858                   PQresultErrorMessage(result), PQresStatus(result_status));
00859          ast_mutex_unlock(&pgsql_lock);
00860          return -1;
00861       }
00862    }
00863 
00864    numrows = atoi(PQcmdTuples(result));
00865    ast_mutex_unlock(&pgsql_lock);
00866 
00867    ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
00868 
00869    /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
00870     * An integer greater than zero indicates the number of rows affected
00871     * Zero indicates that no records were updated
00872     * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
00873     */
00874 
00875    if (numrows >= 0) {
00876       return (int) numrows;
00877    }
00878 
00879    return -1;
00880 }
00881 
00882 static int store_pgsql(const char *database, const char *table, va_list ap)
00883 {
00884    RAII_VAR(PGresult *, result, NULL, PQclear);
00885    Oid insertid;
00886    struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
00887    struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
00888    struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
00889    int pgresult;
00890    const char *newparam, *newval;
00891 
00892    /*
00893     * Ignore database from the extconfig.conf since it was
00894     * configured by res_pgsql.conf.
00895     */
00896    database = dbname;
00897 
00898    if (!table) {
00899       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00900       return -1;
00901    }
00902 
00903    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00904    newparam = va_arg(ap, const char *);
00905    newval = va_arg(ap, const char *);
00906    if (!newparam || !newval) {
00907       ast_log(LOG_WARNING,
00908             "PostgreSQL RealTime: Realtime storage requires at least 1 parameter and 1 value to store.\n");
00909       if (pgsqlConn) {
00910          PQfinish(pgsqlConn);
00911          pgsqlConn = NULL;
00912       }
00913       return -1;
00914    }
00915 
00916    /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
00917    ast_mutex_lock(&pgsql_lock);
00918    if (!pgsql_reconnect(database)) {
00919       ast_mutex_unlock(&pgsql_lock);
00920       return -1;
00921    }
00922 
00923    /* Create the first part of the query using the first parameter/value pairs we just extracted
00924       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00925    ESCAPE_STRING(buf, newparam);
00926    ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
00927    ESCAPE_STRING(buf, newval);
00928    ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
00929    while ((newparam = va_arg(ap, const char *))) {
00930       newval = va_arg(ap, const char *);
00931       ESCAPE_STRING(buf, newparam);
00932       ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
00933       ESCAPE_STRING(buf, newval);
00934       ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
00935    }
00936    ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
00937 
00938    ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
00939 
00940    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql1)))) {
00941       ast_log(LOG_WARNING,
00942             "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00943       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
00944       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
00945       ast_mutex_unlock(&pgsql_lock);
00946       return -1;
00947    } else {
00948       ExecStatusType result_status = PQresultStatus(result);
00949       if (result_status != PGRES_COMMAND_OK
00950          && result_status != PGRES_TUPLES_OK
00951          && result_status != PGRES_NONFATAL_ERROR) {
00952          ast_log(LOG_WARNING,
00953                "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
00954          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
00955          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
00956                   PQresultErrorMessage(result), PQresStatus(result_status));
00957          ast_mutex_unlock(&pgsql_lock);
00958          return -1;
00959       }
00960    }
00961 
00962    insertid = PQoidValue(result);
00963    ast_mutex_unlock(&pgsql_lock);
00964 
00965    ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s, id: %u\n", table, insertid);
00966 
00967    /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
00968     * An integer greater than zero indicates the number of rows affected
00969     * Zero indicates that no records were updated
00970     * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
00971     */
00972 
00973    if (insertid >= 0)
00974       return (int) insertid;
00975 
00976    return -1;
00977 }
00978 
00979 static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
00980 {
00981    RAII_VAR(PGresult *, result, NULL, PQclear);
00982    int numrows = 0;
00983    int pgresult;
00984    struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
00985    struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
00986    const char *newparam, *newval;
00987 
00988    /*
00989     * Ignore database from the extconfig.conf since it was
00990     * configured by res_pgsql.conf.
00991     */
00992    database = dbname;
00993 
00994    if (!table) {
00995       ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
00996       return -1;
00997    }
00998 
00999    /* Get the first parameter and first value in our list of passed paramater/value pairs */
01000    /*newparam = va_arg(ap, const char *);
01001    newval = va_arg(ap, const char *);
01002    if (!newparam || !newval) {*/
01003    if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup))  {
01004       ast_log(LOG_WARNING,
01005             "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
01006       if (pgsqlConn) {
01007          PQfinish(pgsqlConn);
01008          pgsqlConn = NULL;
01009       };
01010       return -1;
01011    }
01012 
01013    /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
01014    ast_mutex_lock(&pgsql_lock);
01015    if (!pgsql_reconnect(database)) {
01016       ast_mutex_unlock(&pgsql_lock);
01017       return -1;
01018    }
01019 
01020 
01021    /* Create the first part of the query using the first parameter/value pairs we just extracted
01022       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
01023 
01024    ESCAPE_STRING(buf1, keyfield);
01025    ESCAPE_STRING(buf2, lookup);
01026    ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
01027    while ((newparam = va_arg(ap, const char *))) {
01028       newval = va_arg(ap, const char *);
01029       ESCAPE_STRING(buf1, newparam);
01030       ESCAPE_STRING(buf2, newval);
01031       ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
01032    }
01033 
01034    ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
01035 
01036    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
01037       ast_log(LOG_WARNING,
01038             "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
01039       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
01040       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
01041       ast_mutex_unlock(&pgsql_lock);
01042       return -1;
01043    } else {
01044       ExecStatusType result_status = PQresultStatus(result);
01045       if (result_status != PGRES_COMMAND_OK
01046          && result_status != PGRES_TUPLES_OK
01047          && result_status != PGRES_NONFATAL_ERROR) {
01048          ast_log(LOG_WARNING,
01049                "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
01050          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
01051          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
01052                   PQresultErrorMessage(result), PQresStatus(result_status));
01053          ast_mutex_unlock(&pgsql_lock);
01054          return -1;
01055       }
01056    }
01057 
01058    numrows = atoi(PQcmdTuples(result));
01059    ast_mutex_unlock(&pgsql_lock);
01060 
01061    ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
01062 
01063    /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
01064     * An integer greater than zero indicates the number of rows affected
01065     * Zero indicates that no records were updated
01066     * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
01067     */
01068 
01069    if (numrows >= 0)
01070       return (int) numrows;
01071 
01072    return -1;
01073 }
01074 
01075 
01076 static struct ast_config *config_pgsql(const char *database, const char *table,
01077                               const char *file, struct ast_config *cfg,
01078                               struct ast_flags flags, const char *suggested_incl, const char *who_asked)
01079 {
01080    RAII_VAR(PGresult *, result, NULL, PQclear);
01081    long num_rows;
01082    struct ast_variable *new_v;
01083    struct ast_category *cur_cat = NULL;
01084    struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
01085    char last[80];
01086    int last_cat_metric = 0;
01087 
01088    last[0] = '\0';
01089 
01090    /*
01091     * Ignore database from the extconfig.conf since it is
01092     * configured by res_pgsql.conf.
01093     */
01094    database = dbname;
01095 
01096    if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
01097       ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
01098       return NULL;
01099    }
01100 
01101    ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
01102          "WHERE filename='%s' and commented=0"
01103          "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
01104 
01105    ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
01106 
01107    /* We now have our complete statement; Lets connect to the server and execute it. */
01108    ast_mutex_lock(&pgsql_lock);
01109    if (!pgsql_reconnect(database)) {
01110       ast_mutex_unlock(&pgsql_lock);
01111       return NULL;
01112    }
01113 
01114    if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
01115       ast_log(LOG_WARNING,
01116             "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", table, database);
01117       ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
01118       ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
01119       ast_mutex_unlock(&pgsql_lock);
01120       return NULL;
01121    } else {
01122       ExecStatusType result_status = PQresultStatus(result);
01123       if (result_status != PGRES_COMMAND_OK
01124          && result_status != PGRES_TUPLES_OK
01125          && result_status != PGRES_NONFATAL_ERROR) {
01126          ast_log(LOG_WARNING,
01127                "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
01128          ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
01129          ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
01130                   PQresultErrorMessage(result), PQresStatus(result_status));
01131          ast_mutex_unlock(&pgsql_lock);
01132          return NULL;
01133       }
01134    }
01135 
01136    if ((num_rows = PQntuples(result)) > 0) {
01137       int rowIndex = 0;
01138 
01139       ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
01140 
01141       for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
01142          char *field_category = PQgetvalue(result, rowIndex, 0);
01143          char *field_var_name = PQgetvalue(result, rowIndex, 1);
01144          char *field_var_val = PQgetvalue(result, rowIndex, 2);
01145          char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
01146          if (!strcmp(field_var_name, "#include")) {
01147             if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
01148                ast_mutex_unlock(&pgsql_lock);
01149                return NULL;
01150             }
01151             continue;
01152          }
01153 
01154          if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
01155             cur_cat = ast_category_new(field_category, "", 99999);
01156             if (!cur_cat)
01157                break;
01158             ast_copy_string(last, field_category, sizeof(last));
01159             last_cat_metric = atoi(field_cat_metric);
01160             ast_category_append(cfg, cur_cat);
01161          }
01162          new_v = ast_variable_new(field_var_name, field_var_val, "");
01163          ast_variable_append(cur_cat, new_v);
01164       }
01165    } else {
01166       ast_log(LOG_WARNING,
01167             "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
01168    }
01169 
01170    ast_mutex_unlock(&pgsql_lock);
01171 
01172    return cfg;
01173 }
01174 
01175 static int require_pgsql(const char *database, const char *tablename, va_list ap)
01176 {
01177    struct columns *column;
01178    struct tables *table;
01179    char *elm;
01180    int type, size, res = 0;
01181 
01182    /*
01183     * Ignore database from the extconfig.conf since it was
01184     * configured by res_pgsql.conf.
01185     */
01186    database = dbname;
01187 
01188    table = find_table(database, tablename);
01189    if (!table) {
01190       ast_log(LOG_WARNING, "Table %s not found in database.  This table should exist if you're using realtime.\n", tablename);
01191       return -1;
01192    }
01193 
01194    while ((elm = va_arg(ap, char *))) {
01195       type = va_arg(ap, require_type);
01196       size = va_arg(ap, int);
01197       AST_LIST_TRAVERSE(&table->columns, column, list) {
01198          if (strcmp(column->name, elm) == 0) {
01199             /* Char can hold anything, as long as it is large enough */
01200             if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
01201                if ((size > column->len) && column->len != -1) {
01202                   ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
01203                   res = -1;
01204                }
01205             } else if (strncmp(column->type, "int", 3) == 0) {
01206                int typesize = atoi(column->type + 3);
01207                /* Integers can hold only other integers */
01208                if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
01209                   type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
01210                   type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
01211                   type == RQ_UINTEGER2) && typesize == 2) {
01212                   ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
01213                   res = -1;
01214                } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
01215                   type == RQ_UINTEGER4) && typesize == 4) {
01216                   ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
01217                   res = -1;
01218                } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
01219                   ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
01220                      column->name,
01221                         type == RQ_CHAR ? "char" :
01222                         type == RQ_DATETIME ? "datetime" :
01223                         type == RQ_DATE ? "date" :
01224                         type == RQ_FLOAT ? "float" :
01225                         "a rather stiff drink ",
01226                      size, column->type);
01227                   res = -1;
01228                }
01229             } else if (strncmp(column->type, "float", 5) == 0) {
01230                if (!ast_rq_is_int(type) && type != RQ_FLOAT) {
01231                   ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
01232                   res = -1;
01233                }
01234             } else if (strncmp(column->type, "timestamp", 9) == 0) {
01235                if (type != RQ_DATETIME && type != RQ_DATE) {
01236                   ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
01237                   res = -1;
01238                }
01239             } else { /* There are other types that no module implements yet */
01240                ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
01241                res = -1;
01242             }
01243             break;
01244          }
01245       }
01246 
01247       if (!column) {
01248          if (requirements == RQ_WARN) {
01249             ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
01250          } else {
01251             struct ast_str *sql = ast_str_create(100);
01252             char fieldtype[15];
01253             PGresult *result;
01254 
01255             if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
01256                /* Size is minimum length; make it at least 50% greater,
01257                 * just to be sure, because PostgreSQL doesn't support
01258                 * resizing columns. */
01259                snprintf(fieldtype, sizeof(fieldtype), "CHAR(%d)",
01260                   size < 15 ? size * 2 :
01261                   (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
01262             } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
01263                snprintf(fieldtype, sizeof(fieldtype), "INT2");
01264             } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
01265                snprintf(fieldtype, sizeof(fieldtype), "INT4");
01266             } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
01267                snprintf(fieldtype, sizeof(fieldtype), "INT8");
01268             } else if (type == RQ_UINTEGER8) {
01269                /* No such type on PostgreSQL */
01270                snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
01271             } else if (type == RQ_FLOAT) {
01272                snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
01273             } else if (type == RQ_DATE) {
01274                snprintf(fieldtype, sizeof(fieldtype), "DATE");
01275             } else if (type == RQ_DATETIME) {
01276                snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
01277             } else {
01278                ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
01279                ast_free(sql);
01280                continue;
01281             }
01282             ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
01283             ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
01284 
01285             ast_mutex_lock(&pgsql_lock);
01286             if (!pgsql_reconnect(database)) {
01287                ast_mutex_unlock(&pgsql_lock);
01288                ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
01289                ast_free(sql);
01290                continue;
01291             }
01292 
01293             ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
01294             result = PQexec(pgsqlConn, ast_str_buffer(sql));
01295             ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
01296             if (PQresultStatus(result) != PGRES_COMMAND_OK) {
01297                ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
01298             }
01299             PQclear(result);
01300             ast_mutex_unlock(&pgsql_lock);
01301 
01302             ast_free(sql);
01303          }
01304       }
01305    }
01306    release_table(table);
01307    return res;
01308 }
01309 
01310 static int unload_pgsql(const char *database, const char *tablename)
01311 {
01312    struct tables *cur;
01313 
01314    /*
01315     * Ignore database from the extconfig.conf since it was
01316     * configured by res_pgsql.conf.
01317     */
01318    database = dbname;
01319 
01320    ast_debug(2, "About to lock table cache list\n");
01321    AST_LIST_LOCK(&psql_tables);
01322    ast_debug(2, "About to traverse table cache list\n");
01323    AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
01324       if (strcmp(cur->name, tablename) == 0) {
01325          ast_debug(2, "About to remove matching cache entry\n");
01326          AST_LIST_REMOVE_CURRENT(list);
01327          ast_debug(2, "About to destroy matching cache entry\n");
01328          destroy_table(cur);
01329          ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
01330          break;
01331       }
01332    }
01333    AST_LIST_TRAVERSE_SAFE_END
01334    AST_LIST_UNLOCK(&psql_tables);
01335    ast_debug(2, "About to return\n");
01336    return cur ? 0 : -1;
01337 }
01338 
01339 static struct ast_config_engine pgsql_engine = {
01340    .name = "pgsql",
01341    .load_func = config_pgsql,
01342    .realtime_func = realtime_pgsql,
01343    .realtime_multi_func = realtime_multi_pgsql,
01344    .store_func = store_pgsql,
01345    .destroy_func = destroy_pgsql,
01346    .update_func = update_pgsql,
01347    .update2_func = update2_pgsql,
01348    .require_func = require_pgsql,
01349    .unload_func = unload_pgsql,
01350 };
01351 
01352 static int load_module(void)
01353 {
01354    if(!parse_config(0))
01355       return AST_MODULE_LOAD_DECLINE;
01356 
01357    ast_config_engine_register(&pgsql_engine);
01358    ast_verb(1, "PostgreSQL RealTime driver loaded.\n");
01359    ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
01360 
01361    return 0;
01362 }
01363 
01364 static int unload_module(void)
01365 {
01366    struct tables *table;
01367    /* Acquire control before doing anything to the module itself. */
01368    ast_mutex_lock(&pgsql_lock);
01369 
01370    if (pgsqlConn) {
01371       PQfinish(pgsqlConn);
01372       pgsqlConn = NULL;
01373    }
01374    ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
01375    ast_config_engine_deregister(&pgsql_engine);
01376    ast_verb(1, "PostgreSQL RealTime unloaded.\n");
01377 
01378    /* Destroy cached table info */
01379    AST_LIST_LOCK(&psql_tables);
01380    while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
01381       destroy_table(table);
01382    }
01383    AST_LIST_UNLOCK(&psql_tables);
01384 
01385    /* Unlock so something else can destroy the lock. */
01386    ast_mutex_unlock(&pgsql_lock);
01387 
01388    return 0;
01389 }
01390 
01391 static int reload(void)
01392 {
01393    parse_config(1);
01394 
01395    return 0;
01396 }
01397 
01398 static int parse_config(int is_reload)
01399 {
01400    struct ast_config *config;
01401    const char *s;
01402    struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
01403 
01404    config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
01405    if (config == CONFIG_STATUS_FILEUNCHANGED) {
01406       return 0;
01407    }
01408 
01409    if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
01410       ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
01411       return 0;
01412    }
01413 
01414    ast_mutex_lock(&pgsql_lock);
01415 
01416    if (pgsqlConn) {
01417       PQfinish(pgsqlConn);
01418       pgsqlConn = NULL;
01419    }
01420 
01421    if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
01422       ast_log(LOG_WARNING,
01423             "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
01424       strcpy(dbuser, "asterisk");
01425    } else {
01426       ast_copy_string(dbuser, s, sizeof(dbuser));
01427    }
01428 
01429    if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
01430       ast_log(LOG_WARNING,
01431             "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
01432       strcpy(dbpass, "asterisk");
01433    } else {
01434       ast_copy_string(dbpass, s, sizeof(dbpass));
01435    }
01436 
01437    if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
01438       ast_log(LOG_WARNING,
01439             "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
01440       dbhost[0] = '\0';
01441    } else {
01442       ast_copy_string(dbhost, s, sizeof(dbhost));
01443    }
01444 
01445    if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
01446       ast_log(LOG_WARNING,
01447             "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
01448       strcpy(dbname, "asterisk");
01449    } else {
01450       ast_copy_string(dbname, s, sizeof(dbname));
01451    }
01452 
01453    if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
01454       ast_log(LOG_WARNING,
01455             "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
01456       dbport = 5432;
01457    } else {
01458       dbport = atoi(s);
01459    }
01460 
01461    if (!ast_strlen_zero(dbhost)) {
01462       /* No socket needed */
01463    } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
01464       ast_log(LOG_WARNING,
01465             "PostgreSQL RealTime: No database socket found, using '/tmp/.s.PGSQL.%d' as default.\n", dbport);
01466       strcpy(dbsock, "/tmp");
01467    } else {
01468       ast_copy_string(dbsock, s, sizeof(dbsock));
01469    }
01470 
01471    if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
01472       ast_log(LOG_WARNING,
01473             "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
01474       requirements = RQ_WARN;
01475    } else if (!strcasecmp(s, "createclose")) {
01476       requirements = RQ_CREATECLOSE;
01477    } else if (!strcasecmp(s, "createchar")) {
01478       requirements = RQ_CREATECHAR;
01479    }
01480 
01481    ast_config_destroy(config);
01482 
01483    if (option_debug) {
01484       if (!ast_strlen_zero(dbhost)) {
01485          ast_debug(1, "PostgreSQL RealTime Host: %s\n", dbhost);
01486          ast_debug(1, "PostgreSQL RealTime Port: %i\n", dbport);
01487       } else {
01488          ast_debug(1, "PostgreSQL RealTime Socket: %s\n", dbsock);
01489       }
01490       ast_debug(1, "PostgreSQL RealTime User: %s\n", dbuser);
01491       ast_debug(1, "PostgreSQL RealTime Password: %s\n", dbpass);
01492       ast_debug(1, "PostgreSQL RealTime DBName: %s\n", dbname);
01493    }
01494 
01495    if (!pgsql_reconnect(NULL)) {
01496       ast_log(LOG_WARNING,
01497             "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
01498       ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
01499    }
01500 
01501    ast_verb(2, "PostgreSQL RealTime reloaded.\n");
01502 
01503    /* Done reloading. Release lock so others can now use driver. */
01504    ast_mutex_unlock(&pgsql_lock);
01505 
01506    return 1;
01507 }
01508 
01509 static int pgsql_reconnect(const char *database)
01510 {
01511    char my_database[50];
01512 
01513    ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
01514 
01515    /* mutex lock should have been locked before calling this function. */
01516 
01517    if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
01518       PQfinish(pgsqlConn);
01519       pgsqlConn = NULL;
01520    }
01521 
01522    /* DB password can legitimately be 0-length */
01523    if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
01524       struct ast_str *connInfo = ast_str_create(128);
01525 
01526       ast_str_set(&connInfo, 0, "host=%s port=%d dbname=%s user=%s",
01527          S_OR(dbhost, dbsock), dbport, my_database, dbuser);
01528       if (!ast_strlen_zero(dbpass))
01529          ast_str_append(&connInfo, 0, " password=%s", dbpass);
01530 
01531       ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
01532       pgsqlConn = PQconnectdb(ast_str_buffer(connInfo));
01533       ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
01534       ast_free(connInfo);
01535       connInfo = NULL;
01536 
01537       ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
01538       if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
01539          ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
01540          connect_time = time(NULL);
01541          version = PQserverVersion(pgsqlConn);
01542          return 1;
01543       } else {
01544          ast_log(LOG_ERROR,
01545                "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
01546                my_database, dbhost, PQresultErrorMessage(NULL));
01547          return 0;
01548       }
01549    } else {
01550       ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
01551       return 1;
01552    }
01553 }
01554 
01555 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01556 {
01557    struct tables *cur;
01558    int l, which;
01559    char *ret = NULL;
01560 
01561    switch (cmd) {
01562    case CLI_INIT:
01563       e->command = "realtime show pgsql cache";
01564       e->usage =
01565          "Usage: realtime show pgsql cache [<table>]\n"
01566          "       Shows table cache for the PostgreSQL RealTime driver\n";
01567       return NULL;
01568    case CLI_GENERATE:
01569       if (a->argc != 4) {
01570          return NULL;
01571       }
01572       l = strlen(a->word);
01573       which = 0;
01574       AST_LIST_LOCK(&psql_tables);
01575       AST_LIST_TRAVERSE(&psql_tables, cur, list) {
01576          if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
01577             ret = ast_strdup(cur->name);
01578             break;
01579          }
01580       }
01581       AST_LIST_UNLOCK(&psql_tables);
01582       return ret;
01583    }
01584 
01585    if (a->argc == 4) {
01586       /* List of tables */
01587       AST_LIST_LOCK(&psql_tables);
01588       AST_LIST_TRAVERSE(&psql_tables, cur, list) {
01589          ast_cli(a->fd, "%s\n", cur->name);
01590       }
01591       AST_LIST_UNLOCK(&psql_tables);
01592    } else if (a->argc == 5) {
01593       /* List of columns */
01594       if ((cur = find_table(NULL, a->argv[4]))) {
01595          struct columns *col;
01596          ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
01597          ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
01598          AST_LIST_TRAVERSE(&cur->columns, col, list) {
01599             ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
01600          }
01601          release_table(cur);
01602       } else {
01603          ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
01604       }
01605    }
01606    return 0;
01607 }
01608 
01609 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01610 {
01611    char status[256], credentials[100] = "";
01612    int ctimesec = time(NULL) - connect_time;
01613 
01614    switch (cmd) {
01615    case CLI_INIT:
01616       e->command = "realtime show pgsql status";
01617       e->usage =
01618          "Usage: realtime show pgsql status\n"
01619          "       Shows connection information for the PostgreSQL RealTime driver\n";
01620       return NULL;
01621    case CLI_GENERATE:
01622       return NULL;
01623    }
01624 
01625    if (a->argc != 4)
01626       return CLI_SHOWUSAGE;
01627 
01628    if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
01629       if (!ast_strlen_zero(dbhost))
01630          snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
01631       else if (!ast_strlen_zero(dbsock))
01632          snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
01633       else
01634          snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
01635 
01636       if (!ast_strlen_zero(dbuser))
01637          snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
01638 
01639       if (ctimesec > 31536000)
01640          ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
01641                status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
01642                (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
01643       else if (ctimesec > 86400)
01644          ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
01645                credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
01646                ctimesec % 60);
01647       else if (ctimesec > 3600)
01648          ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
01649                ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
01650       else if (ctimesec > 60)
01651          ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
01652                ctimesec % 60);
01653       else
01654          ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
01655 
01656       return CLI_SUCCESS;
01657    } else {
01658       return CLI_FAILURE;
01659    }
01660 }
01661 
01662 /* needs usecount semantics defined */
01663 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL RealTime Configuration Driver",
01664       .load = load_module,
01665       .unload = unload_module,
01666       .reload = reload,
01667       .load_pri = AST_MODPRI_REALTIME_DRIVER,
01668           );