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