res_config_pgsql.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999-2010, Digium, Inc.
  5. *
  6. * Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
  7. * Mark Spencer <markster@digium.com> - Asterisk Author
  8. * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
  9. *
  10. * res_config_pgsql.c <PostgreSQL plugin for RealTime configuration engine>
  11. *
  12. * v1.0 - (07-11-05) - Initial version based on res_config_mysql v2.0
  13. */
  14. /*! \file
  15. *
  16. * \brief PostgreSQL plugin for Asterisk RealTime Architecture
  17. *
  18. * \author Mark Spencer <markster@digium.com>
  19. * \author Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
  20. *
  21. * PostgreSQL http://www.postgresql.org
  22. */
  23. /*** MODULEINFO
  24. <depend>pgsql</depend>
  25. <support_level>extended</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <libpq-fe.h> /* PostgreSQL */
  30. #include "asterisk/file.h"
  31. #include "asterisk/channel.h"
  32. #include "asterisk/pbx.h"
  33. #include "asterisk/config.h"
  34. #include "asterisk/module.h"
  35. #include "asterisk/lock.h"
  36. #include "asterisk/utils.h"
  37. #include "asterisk/cli.h"
  38. AST_MUTEX_DEFINE_STATIC(pgsql_lock);
  39. AST_THREADSTORAGE(sql_buf);
  40. AST_THREADSTORAGE(findtable_buf);
  41. AST_THREADSTORAGE(where_buf);
  42. AST_THREADSTORAGE(escapebuf_buf);
  43. AST_THREADSTORAGE(semibuf_buf);
  44. #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
  45. static PGconn *pgsqlConn = NULL;
  46. static int version;
  47. #define has_schema_support (version > 70300 ? 1 : 0)
  48. #define USE_BACKSLASH_AS_STRING (version >= 90100 ? 1 : 0)
  49. #define MAX_DB_OPTION_SIZE 64
  50. struct columns {
  51. char *name;
  52. char *type;
  53. int len;
  54. unsigned int notnull:1;
  55. unsigned int hasdefault:1;
  56. AST_LIST_ENTRY(columns) list;
  57. };
  58. struct tables {
  59. ast_rwlock_t lock;
  60. AST_LIST_HEAD_NOLOCK(psql_columns, columns) columns;
  61. AST_LIST_ENTRY(tables) list;
  62. char name[0];
  63. };
  64. static AST_LIST_HEAD_STATIC(psql_tables, tables);
  65. static char dbhost[MAX_DB_OPTION_SIZE] = "";
  66. static char dbuser[MAX_DB_OPTION_SIZE] = "";
  67. static char dbpass[MAX_DB_OPTION_SIZE] = "";
  68. static char dbname[MAX_DB_OPTION_SIZE] = "";
  69. static char dbappname[MAX_DB_OPTION_SIZE] = "";
  70. static char dbsock[MAX_DB_OPTION_SIZE] = "";
  71. static int dbport = 5432;
  72. static time_t connect_time = 0;
  73. static int parse_config(int reload);
  74. static int pgsql_reconnect(const char *database);
  75. static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  76. static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  77. static enum { RQ_WARN, RQ_CREATECLOSE, RQ_CREATECHAR } requirements;
  78. static struct ast_cli_entry cli_realtime[] = {
  79. AST_CLI_DEFINE(handle_cli_realtime_pgsql_status, "Shows connection information for the PostgreSQL RealTime driver"),
  80. AST_CLI_DEFINE(handle_cli_realtime_pgsql_cache, "Shows cached tables within the PostgreSQL realtime driver"),
  81. };
  82. #define ESCAPE_STRING(buffer, stringname) \
  83. do { \
  84. int len = strlen(stringname); \
  85. struct ast_str *semi = ast_str_thread_get(&semibuf_buf, len * 3 + 1); \
  86. const char *chunk = stringname; \
  87. ast_str_reset(semi); \
  88. for (; *chunk; chunk++) { \
  89. if (strchr(";^", *chunk)) { \
  90. ast_str_append(&semi, 0, "^%02hhX", *chunk); \
  91. } else { \
  92. ast_str_append(&semi, 0, "%c", *chunk); \
  93. } \
  94. } \
  95. if (ast_str_strlen(semi) > (ast_str_size(buffer) - 1) / 2) { \
  96. ast_str_make_space(&buffer, ast_str_strlen(semi) * 2 + 1); \
  97. } \
  98. PQescapeStringConn(pgsqlConn, ast_str_buffer(buffer), ast_str_buffer(semi), ast_str_size(buffer), &pgresult); \
  99. } while (0)
  100. static void destroy_table(struct tables *table)
  101. {
  102. struct columns *column;
  103. ast_rwlock_wrlock(&table->lock);
  104. while ((column = AST_LIST_REMOVE_HEAD(&table->columns, list))) {
  105. ast_free(column);
  106. }
  107. ast_rwlock_unlock(&table->lock);
  108. ast_rwlock_destroy(&table->lock);
  109. ast_free(table);
  110. }
  111. /*! \brief Helper function for pgsql_exec. For running querys, use pgsql_exec()
  112. *
  113. * Connect if not currently connected. Run the given query.
  114. *
  115. * \param database database name we are connected to (used for error logging)
  116. * \param tablename table name we are connected to (used for error logging)
  117. * \param sql sql query string to execute
  118. * \param result pointer for where to store the result handle
  119. *
  120. * \return -1 on fatal query error
  121. * \return -2 on query failure that resulted in disconnection
  122. * \return 0 on success
  123. *
  124. * \note see pgsql_exec for full example
  125. */
  126. static int _pgsql_exec(const char *database, const char *tablename, const char *sql, PGresult **result)
  127. {
  128. ExecStatusType result_status;
  129. if (!pgsqlConn) {
  130. ast_debug(1, "PostgreSQL connection not defined, connecting\n");
  131. if (pgsql_reconnect(database) != 1) {
  132. ast_log(LOG_NOTICE, "reconnect failed\n");
  133. *result = NULL;
  134. return -1;
  135. }
  136. ast_debug(1, "PostgreSQL connection successful\n");
  137. }
  138. *result = PQexec(pgsqlConn, sql);
  139. result_status = PQresultStatus(*result);
  140. if (result_status != PGRES_COMMAND_OK
  141. && result_status != PGRES_TUPLES_OK
  142. && result_status != PGRES_NONFATAL_ERROR) {
  143. ast_log(LOG_ERROR, "PostgreSQL RealTime: Failed to query '%s@%s'.\n", tablename, database);
  144. ast_log(LOG_ERROR, "PostgreSQL RealTime: Query Failed: %s\n", sql);
  145. ast_log(LOG_ERROR, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
  146. PQresultErrorMessage(*result),
  147. PQresStatus(result_status));
  148. /* we may have tried to run a command on a disconnected/disconnecting handle */
  149. /* are we no longer connected to the database... if not try again */
  150. if (PQstatus(pgsqlConn) != CONNECTION_OK) {
  151. PQfinish(pgsqlConn);
  152. pgsqlConn = NULL;
  153. return -2;
  154. }
  155. /* connection still okay, which means the query is just plain bad */
  156. return -1;
  157. }
  158. ast_debug(1, "PostgreSQL query successful: %s\n", sql);
  159. return 0;
  160. }
  161. /*! \brief Do a postgres query, with reconnection support
  162. *
  163. * Connect if not currently connected. Run the given query
  164. * and if we're disconnected afterwards, reconnect and query again.
  165. *
  166. * \param database database name we are connected to (used for error logging)
  167. * \param tablename table name we are connected to (used for error logging)
  168. * \param sql sql query string to execute
  169. * \param result pointer for where to store the result handle
  170. *
  171. * \return -1 on query failure
  172. * \return 0 on success
  173. *
  174. * \code
  175. * int i, rows;
  176. * PGresult *result;
  177. * char *field_name, *field_type, *field_len, *field_notnull, *field_default;
  178. *
  179. * pgsql_exec("db", "table", "SELECT 1", &result)
  180. *
  181. * rows = PQntuples(result);
  182. * for (i = 0; i < rows; i++) {
  183. * field_name = PQgetvalue(result, i, 0);
  184. * field_type = PQgetvalue(result, i, 1);
  185. * field_len = PQgetvalue(result, i, 2);
  186. * field_notnull = PQgetvalue(result, i, 3);
  187. * field_default = PQgetvalue(result, i, 4);
  188. * }
  189. * \endcode
  190. */
  191. static int pgsql_exec(const char *database, const char *tablename, const char *sql, PGresult **result)
  192. {
  193. int attempts = 0;
  194. int res;
  195. /* Try the query, note failure if any */
  196. /* On first failure, reconnect and try again (_pgsql_exec handles reconnect) */
  197. /* On second failure, treat as fatal query error */
  198. while (attempts++ < 2) {
  199. ast_debug(1, "PostgreSQL query attempt %d\n", attempts);
  200. res = _pgsql_exec(database, tablename, sql, result);
  201. if (res == 0) {
  202. if (attempts > 1) {
  203. ast_log(LOG_NOTICE, "PostgreSQL RealTime: Query finally succeeded: %s\n", sql);
  204. }
  205. return 0;
  206. }
  207. if (res == -1) {
  208. return -1; /* Still connected to db, but could not process query (fatal error) */
  209. }
  210. /* res == -2 (query on a disconnected handle) */
  211. ast_debug(1, "PostgreSQL query attempt %d failed, trying again\n", attempts);
  212. }
  213. return -1;
  214. }
  215. static struct tables *find_table(const char *database, const char *orig_tablename)
  216. {
  217. struct columns *column;
  218. struct tables *table;
  219. struct ast_str *sql = ast_str_thread_get(&findtable_buf, 330);
  220. RAII_VAR(PGresult *, result, NULL, PQclear);
  221. int exec_result;
  222. char *fname, *ftype, *flen, *fnotnull, *fdef;
  223. int i, rows;
  224. AST_LIST_LOCK(&psql_tables);
  225. AST_LIST_TRAVERSE(&psql_tables, table, list) {
  226. if (!strcasecmp(table->name, orig_tablename)) {
  227. ast_debug(1, "Found table in cache; now locking\n");
  228. ast_rwlock_rdlock(&table->lock);
  229. ast_debug(1, "Lock cached table; now returning\n");
  230. AST_LIST_UNLOCK(&psql_tables);
  231. return table;
  232. }
  233. }
  234. if (database == NULL) {
  235. AST_LIST_UNLOCK(&psql_tables);
  236. return NULL;
  237. }
  238. ast_debug(1, "Table '%s' not found in cache, querying now\n", orig_tablename);
  239. /* Not found, scan the table */
  240. if (has_schema_support) {
  241. char *schemaname, *tablename;
  242. if (strchr(orig_tablename, '.')) {
  243. schemaname = ast_strdupa(orig_tablename);
  244. tablename = strchr(schemaname, '.');
  245. *tablename++ = '\0';
  246. } else {
  247. schemaname = "";
  248. tablename = ast_strdupa(orig_tablename);
  249. }
  250. /* Escape special characters in schemaname */
  251. if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
  252. char *tmp = schemaname, *ptr;
  253. ptr = schemaname = ast_alloca(strlen(tmp) * 2 + 1);
  254. for (; *tmp; tmp++) {
  255. if (strchr("\\'", *tmp)) {
  256. *ptr++ = *tmp;
  257. }
  258. *ptr++ = *tmp;
  259. }
  260. *ptr = '\0';
  261. }
  262. /* Escape special characters in tablename */
  263. if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
  264. char *tmp = tablename, *ptr;
  265. ptr = tablename = ast_alloca(strlen(tmp) * 2 + 1);
  266. for (; *tmp; tmp++) {
  267. if (strchr("\\'", *tmp)) {
  268. *ptr++ = *tmp;
  269. }
  270. *ptr++ = *tmp;
  271. }
  272. *ptr = '\0';
  273. }
  274. 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",
  275. tablename,
  276. ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
  277. } else {
  278. /* Escape special characters in tablename */
  279. if (strchr(orig_tablename, '\\') || strchr(orig_tablename, '\'')) {
  280. const char *tmp = orig_tablename;
  281. char *ptr;
  282. orig_tablename = ptr = ast_alloca(strlen(tmp) * 2 + 1);
  283. for (; *tmp; tmp++) {
  284. if (strchr("\\'", *tmp)) {
  285. *ptr++ = *tmp;
  286. }
  287. *ptr++ = *tmp;
  288. }
  289. *ptr = '\0';
  290. }
  291. 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);
  292. }
  293. ast_mutex_lock(&pgsql_lock);
  294. exec_result = pgsql_exec(database, orig_tablename, ast_str_buffer(sql), &result);
  295. ast_mutex_unlock(&pgsql_lock);
  296. ast_debug(1, "Query of table structure complete. Now retrieving results.\n");
  297. if (exec_result != 0) {
  298. ast_log(LOG_ERROR, "Failed to query database columns for table %s\n", orig_tablename);
  299. AST_LIST_UNLOCK(&psql_tables);
  300. return NULL;
  301. }
  302. if (!(table = ast_calloc(1, sizeof(*table) + strlen(orig_tablename) + 1))) {
  303. ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
  304. AST_LIST_UNLOCK(&psql_tables);
  305. return NULL;
  306. }
  307. strcpy(table->name, orig_tablename); /* SAFE */
  308. ast_rwlock_init(&table->lock);
  309. AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
  310. rows = PQntuples(result);
  311. for (i = 0; i < rows; i++) {
  312. fname = PQgetvalue(result, i, 0);
  313. ftype = PQgetvalue(result, i, 1);
  314. flen = PQgetvalue(result, i, 2);
  315. fnotnull = PQgetvalue(result, i, 3);
  316. fdef = PQgetvalue(result, i, 4);
  317. ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
  318. if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + 2))) {
  319. ast_log(LOG_ERROR, "Unable to allocate column element for %s, %s\n", orig_tablename, fname);
  320. destroy_table(table);
  321. AST_LIST_UNLOCK(&psql_tables);
  322. return NULL;
  323. }
  324. if (strcmp(flen, "-1") == 0) {
  325. /* Some types, like chars, have the length stored in a different field */
  326. flen = PQgetvalue(result, i, 5);
  327. sscanf(flen, "%30d", &column->len);
  328. column->len -= 4;
  329. } else {
  330. sscanf(flen, "%30d", &column->len);
  331. }
  332. column->name = (char *)column + sizeof(*column);
  333. column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
  334. strcpy(column->name, fname);
  335. strcpy(column->type, ftype);
  336. if (*fnotnull == 't') {
  337. column->notnull = 1;
  338. } else {
  339. column->notnull = 0;
  340. }
  341. if (!ast_strlen_zero(fdef)) {
  342. column->hasdefault = 1;
  343. } else {
  344. column->hasdefault = 0;
  345. }
  346. AST_LIST_INSERT_TAIL(&table->columns, column, list);
  347. }
  348. AST_LIST_INSERT_TAIL(&psql_tables, table, list);
  349. ast_rwlock_rdlock(&table->lock);
  350. AST_LIST_UNLOCK(&psql_tables);
  351. return table;
  352. }
  353. #define release_table(table) ast_rwlock_unlock(&(table)->lock);
  354. static struct columns *find_column(struct tables *t, const char *colname)
  355. {
  356. struct columns *column;
  357. /* Check that the column exists in the table */
  358. AST_LIST_TRAVERSE(&t->columns, column, list) {
  359. if (strcmp(column->name, colname) == 0) {
  360. return column;
  361. }
  362. }
  363. return NULL;
  364. }
  365. #define IS_SQL_LIKE_CLAUSE(x) ((x) && ast_ends_with(x, " LIKE"))
  366. #define ESCAPE_CLAUSE (USE_BACKSLASH_AS_STRING ? " ESCAPE '\\'" : " ESCAPE '\\\\'")
  367. static struct ast_variable *realtime_pgsql(const char *database, const char *tablename, const struct ast_variable *fields)
  368. {
  369. RAII_VAR(PGresult *, result, NULL, PQclear);
  370. int num_rows = 0, pgresult;
  371. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  372. struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
  373. char *stringp;
  374. char *chunk;
  375. char *op;
  376. char *escape = "";
  377. const struct ast_variable *field = fields;
  378. struct ast_variable *var = NULL, *prev = NULL;
  379. /*
  380. * Ignore database from the extconfig.conf since it was
  381. * configured by res_pgsql.conf.
  382. */
  383. database = dbname;
  384. if (!tablename) {
  385. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  386. return NULL;
  387. }
  388. /*
  389. * Must connect to the server before anything else as ESCAPE_STRING()
  390. * uses pgsqlConn
  391. */
  392. ast_mutex_lock(&pgsql_lock);
  393. if (!pgsql_reconnect(database)) {
  394. ast_mutex_unlock(&pgsql_lock);
  395. return NULL;
  396. }
  397. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  398. if (!field) {
  399. ast_log(LOG_WARNING,
  400. "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
  401. if (pgsqlConn) {
  402. PQfinish(pgsqlConn);
  403. pgsqlConn = NULL;
  404. }
  405. ast_mutex_unlock(&pgsql_lock);
  406. return NULL;
  407. }
  408. /* Create the first part of the query using the first parameter/value pairs we just extracted
  409. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  410. if (!strchr(field->name, ' ')) {
  411. op = " =";
  412. } else {
  413. op = "";
  414. if (IS_SQL_LIKE_CLAUSE(field->name)) {
  415. escape = ESCAPE_CLAUSE;
  416. }
  417. }
  418. ESCAPE_STRING(escapebuf, field->value);
  419. if (pgresult) {
  420. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  421. ast_mutex_unlock(&pgsql_lock);
  422. return NULL;
  423. }
  424. ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'%s", tablename, field->name, op, ast_str_buffer(escapebuf), escape);
  425. while ((field = field->next)) {
  426. escape = "";
  427. if (!strchr(field->name, ' ')) {
  428. op = " =";
  429. } else {
  430. op = "";
  431. if (IS_SQL_LIKE_CLAUSE(field->name)) {
  432. escape = ESCAPE_CLAUSE;
  433. }
  434. }
  435. ESCAPE_STRING(escapebuf, field->value);
  436. if (pgresult) {
  437. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  438. ast_mutex_unlock(&pgsql_lock);
  439. return NULL;
  440. }
  441. ast_str_append(&sql, 0, " AND %s%s '%s'%s", field->name, op, ast_str_buffer(escapebuf), escape);
  442. }
  443. /* We now have our complete statement; Lets connect to the server and execute it. */
  444. if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
  445. ast_mutex_unlock(&pgsql_lock);
  446. return NULL;
  447. }
  448. ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
  449. if ((num_rows = PQntuples(result)) > 0) {
  450. int i = 0;
  451. int rowIndex = 0;
  452. int numFields = PQnfields(result);
  453. char **fieldnames = NULL;
  454. ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
  455. if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
  456. ast_mutex_unlock(&pgsql_lock);
  457. return NULL;
  458. }
  459. for (i = 0; i < numFields; i++)
  460. fieldnames[i] = PQfname(result, i);
  461. for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
  462. for (i = 0; i < numFields; i++) {
  463. stringp = PQgetvalue(result, rowIndex, i);
  464. while (stringp) {
  465. chunk = strsep(&stringp, ";");
  466. if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
  467. if (prev) {
  468. prev->next = ast_variable_new(fieldnames[i], chunk, "");
  469. if (prev->next) {
  470. prev = prev->next;
  471. }
  472. } else {
  473. prev = var = ast_variable_new(fieldnames[i], chunk, "");
  474. }
  475. }
  476. }
  477. }
  478. }
  479. ast_free(fieldnames);
  480. } else {
  481. ast_debug(1, "Postgresql RealTime: Could not find any rows in table %s@%s.\n", tablename, database);
  482. }
  483. ast_mutex_unlock(&pgsql_lock);
  484. return var;
  485. }
  486. static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, const struct ast_variable *fields)
  487. {
  488. RAII_VAR(PGresult *, result, NULL, PQclear);
  489. int num_rows = 0, pgresult;
  490. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  491. struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
  492. const struct ast_variable *field = fields;
  493. const char *initfield = NULL;
  494. char *stringp;
  495. char *chunk;
  496. char *op;
  497. char *escape = "";
  498. struct ast_variable *var = NULL;
  499. struct ast_config *cfg = NULL;
  500. struct ast_category *cat = NULL;
  501. /*
  502. * Ignore database from the extconfig.conf since it was
  503. * configured by res_pgsql.conf.
  504. */
  505. database = dbname;
  506. if (!table) {
  507. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  508. return NULL;
  509. }
  510. if (!(cfg = ast_config_new()))
  511. return NULL;
  512. /*
  513. * Must connect to the server before anything else as ESCAPE_STRING()
  514. * uses pgsqlConn
  515. */
  516. ast_mutex_lock(&pgsql_lock);
  517. if (!pgsql_reconnect(database)) {
  518. ast_mutex_unlock(&pgsql_lock);
  519. return NULL;
  520. }
  521. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  522. if (!field) {
  523. ast_log(LOG_WARNING,
  524. "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
  525. if (pgsqlConn) {
  526. PQfinish(pgsqlConn);
  527. pgsqlConn = NULL;
  528. }
  529. ast_mutex_unlock(&pgsql_lock);
  530. ast_config_destroy(cfg);
  531. return NULL;
  532. }
  533. initfield = ast_strdupa(field->name);
  534. if ((op = strchr(initfield, ' '))) {
  535. *op = '\0';
  536. }
  537. /* Create the first part of the query using the first parameter/value pairs we just extracted
  538. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  539. if (!strchr(field->name, ' ')) {
  540. op = " =";
  541. escape = "";
  542. } else {
  543. op = "";
  544. if (IS_SQL_LIKE_CLAUSE(field->name)) {
  545. escape = ESCAPE_CLAUSE;
  546. }
  547. }
  548. ESCAPE_STRING(escapebuf, field->value);
  549. if (pgresult) {
  550. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  551. ast_mutex_unlock(&pgsql_lock);
  552. ast_config_destroy(cfg);
  553. return NULL;
  554. }
  555. ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'%s", table, field->name, op, ast_str_buffer(escapebuf), escape);
  556. while ((field = field->next)) {
  557. escape = "";
  558. if (!strchr(field->name, ' ')) {
  559. op = " =";
  560. escape = "";
  561. } else {
  562. op = "";
  563. if (IS_SQL_LIKE_CLAUSE(field->name)) {
  564. escape = ESCAPE_CLAUSE;
  565. }
  566. }
  567. ESCAPE_STRING(escapebuf, field->value);
  568. if (pgresult) {
  569. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  570. ast_mutex_unlock(&pgsql_lock);
  571. ast_config_destroy(cfg);
  572. return NULL;
  573. }
  574. ast_str_append(&sql, 0, " AND %s%s '%s'%s", field->name, op, ast_str_buffer(escapebuf), escape);
  575. }
  576. if (initfield) {
  577. ast_str_append(&sql, 0, " ORDER BY %s", initfield);
  578. }
  579. /* We now have our complete statement; Lets connect to the server and execute it. */
  580. if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
  581. ast_mutex_unlock(&pgsql_lock);
  582. ast_config_destroy(cfg);
  583. return NULL;
  584. } else {
  585. ExecStatusType result_status = PQresultStatus(result);
  586. if (result_status != PGRES_COMMAND_OK
  587. && result_status != PGRES_TUPLES_OK
  588. && result_status != PGRES_NONFATAL_ERROR) {
  589. ast_log(LOG_WARNING,
  590. "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
  591. ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
  592. ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
  593. PQresultErrorMessage(result), PQresStatus(result_status));
  594. ast_mutex_unlock(&pgsql_lock);
  595. ast_config_destroy(cfg);
  596. return NULL;
  597. }
  598. }
  599. ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
  600. if ((num_rows = PQntuples(result)) > 0) {
  601. int numFields = PQnfields(result);
  602. int i = 0;
  603. int rowIndex = 0;
  604. char **fieldnames = NULL;
  605. ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
  606. if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
  607. ast_mutex_unlock(&pgsql_lock);
  608. ast_config_destroy(cfg);
  609. return NULL;
  610. }
  611. for (i = 0; i < numFields; i++)
  612. fieldnames[i] = PQfname(result, i);
  613. for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
  614. var = NULL;
  615. cat = ast_category_new_anonymous();
  616. if (!cat) {
  617. continue;
  618. }
  619. for (i = 0; i < numFields; i++) {
  620. stringp = PQgetvalue(result, rowIndex, i);
  621. while (stringp) {
  622. chunk = strsep(&stringp, ";");
  623. if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
  624. if (initfield && !strcmp(initfield, fieldnames[i])) {
  625. ast_category_rename(cat, chunk);
  626. }
  627. var = ast_variable_new(fieldnames[i], chunk, "");
  628. ast_variable_append(cat, var);
  629. }
  630. }
  631. }
  632. ast_category_append(cfg, cat);
  633. }
  634. ast_free(fieldnames);
  635. } else {
  636. ast_debug(1, "PostgreSQL RealTime: Could not find any rows in table %s.\n", table);
  637. }
  638. ast_mutex_unlock(&pgsql_lock);
  639. return cfg;
  640. }
  641. static int update_pgsql(const char *database, const char *tablename, const char *keyfield,
  642. const char *lookup, const struct ast_variable *fields)
  643. {
  644. RAII_VAR(PGresult *, result, NULL, PQclear);
  645. int numrows = 0, pgresult;
  646. const struct ast_variable *field = fields;
  647. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  648. struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
  649. struct tables *table;
  650. struct columns *column = NULL;
  651. /*
  652. * Ignore database from the extconfig.conf since it was
  653. * configured by res_pgsql.conf.
  654. */
  655. database = dbname;
  656. if (!tablename) {
  657. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  658. return -1;
  659. }
  660. if (!(table = find_table(database, tablename))) {
  661. ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
  662. return -1;
  663. }
  664. /*
  665. * Must connect to the server before anything else as ESCAPE_STRING()
  666. * uses pgsqlConn
  667. */
  668. ast_mutex_lock(&pgsql_lock);
  669. if (!pgsql_reconnect(database)) {
  670. ast_mutex_unlock(&pgsql_lock);
  671. release_table(table);
  672. return -1;
  673. }
  674. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  675. if (!field) {
  676. ast_log(LOG_WARNING,
  677. "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
  678. if (pgsqlConn) {
  679. PQfinish(pgsqlConn);
  680. pgsqlConn = NULL;
  681. }
  682. ast_mutex_unlock(&pgsql_lock);
  683. release_table(table);
  684. return -1;
  685. }
  686. /* Check that the column exists in the table */
  687. AST_LIST_TRAVERSE(&table->columns, column, list) {
  688. if (strcmp(column->name, field->name) == 0) {
  689. break;
  690. }
  691. }
  692. if (!column) {
  693. ast_log(LOG_ERROR, "PostgreSQL RealTime: Updating on column '%s', but that column does not exist within the table '%s'!\n", field->name, tablename);
  694. ast_mutex_unlock(&pgsql_lock);
  695. release_table(table);
  696. return -1;
  697. }
  698. /* Create the first part of the query using the first parameter/value pairs we just extracted
  699. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  700. ESCAPE_STRING(escapebuf, field->value);
  701. if (pgresult) {
  702. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  703. ast_mutex_unlock(&pgsql_lock);
  704. release_table(table);
  705. return -1;
  706. }
  707. ast_str_set(&sql, 0, "UPDATE %s SET %s = '%s'", tablename, field->name, ast_str_buffer(escapebuf));
  708. while ((field = field->next)) {
  709. if (!find_column(table, field->name)) {
  710. ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s', but column does not exist!\n", field->name, tablename);
  711. continue;
  712. }
  713. ESCAPE_STRING(escapebuf, field->value);
  714. if (pgresult) {
  715. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  716. ast_mutex_unlock(&pgsql_lock);
  717. release_table(table);
  718. return -1;
  719. }
  720. ast_str_append(&sql, 0, ", %s = '%s'", field->name, ast_str_buffer(escapebuf));
  721. }
  722. release_table(table);
  723. ESCAPE_STRING(escapebuf, lookup);
  724. if (pgresult) {
  725. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", lookup);
  726. ast_mutex_unlock(&pgsql_lock);
  727. return -1;
  728. }
  729. ast_str_append(&sql, 0, " WHERE %s = '%s'", keyfield, ast_str_buffer(escapebuf));
  730. ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
  731. /* We now have our complete statement; Lets connect to the server and execute it. */
  732. if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
  733. ast_mutex_unlock(&pgsql_lock);
  734. return -1;
  735. } else {
  736. ExecStatusType result_status = PQresultStatus(result);
  737. if (result_status != PGRES_COMMAND_OK
  738. && result_status != PGRES_TUPLES_OK
  739. && result_status != PGRES_NONFATAL_ERROR) {
  740. ast_log(LOG_WARNING,
  741. "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
  742. ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
  743. ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
  744. PQresultErrorMessage(result), PQresStatus(result_status));
  745. ast_mutex_unlock(&pgsql_lock);
  746. return -1;
  747. }
  748. }
  749. numrows = atoi(PQcmdTuples(result));
  750. ast_mutex_unlock(&pgsql_lock);
  751. ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
  752. /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
  753. * An integer greater than zero indicates the number of rows affected
  754. * Zero indicates that no records were updated
  755. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  756. */
  757. if (numrows >= 0)
  758. return (int) numrows;
  759. return -1;
  760. }
  761. static int update2_pgsql(const char *database, const char *tablename, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
  762. {
  763. RAII_VAR(PGresult *, result, NULL, PQclear);
  764. int numrows = 0, pgresult, first = 1;
  765. struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
  766. const struct ast_variable *field;
  767. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  768. struct ast_str *where = ast_str_thread_get(&where_buf, 100);
  769. struct tables *table;
  770. /*
  771. * Ignore database from the extconfig.conf since it was
  772. * configured by res_pgsql.conf.
  773. */
  774. database = dbname;
  775. if (!tablename) {
  776. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  777. return -1;
  778. }
  779. if (!escapebuf || !sql || !where) {
  780. /* Memory error, already handled */
  781. return -1;
  782. }
  783. if (!(table = find_table(database, tablename))) {
  784. ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
  785. return -1;
  786. }
  787. /*
  788. * Must connect to the server before anything else as ESCAPE_STRING()
  789. * uses pgsqlConn
  790. */
  791. ast_mutex_lock(&pgsql_lock);
  792. if (!pgsql_reconnect(database)) {
  793. ast_mutex_unlock(&pgsql_lock);
  794. release_table(table);
  795. return -1;
  796. }
  797. ast_str_set(&sql, 0, "UPDATE %s SET", tablename);
  798. ast_str_set(&where, 0, " WHERE");
  799. for (field = lookup_fields; field; field = field->next) {
  800. if (!find_column(table, field->name)) {
  801. ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", field->name, tablename, database);
  802. ast_mutex_unlock(&pgsql_lock);
  803. release_table(table);
  804. return -1;
  805. }
  806. ESCAPE_STRING(escapebuf, field->value);
  807. if (pgresult) {
  808. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  809. ast_mutex_unlock(&pgsql_lock);
  810. release_table(table);
  811. return -1;
  812. }
  813. ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", field->name, ast_str_buffer(escapebuf));
  814. first = 0;
  815. }
  816. if (first) {
  817. ast_log(LOG_WARNING,
  818. "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
  819. if (pgsqlConn) {
  820. PQfinish(pgsqlConn);
  821. pgsqlConn = NULL;
  822. }
  823. ast_mutex_unlock(&pgsql_lock);
  824. release_table(table);
  825. return -1;
  826. }
  827. /* Now retrieve the columns to update */
  828. first = 1;
  829. for (field = update_fields; field; field = field->next) {
  830. /* If the column is not within the table, then skip it */
  831. if (!find_column(table, field->name)) {
  832. ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", field->name, tablename, database);
  833. continue;
  834. }
  835. ESCAPE_STRING(escapebuf, field->value);
  836. if (pgresult) {
  837. ast_log(LOG_ERROR, "PostgreSQL RealTime: detected invalid input: '%s'\n", field->value);
  838. ast_mutex_unlock(&pgsql_lock);
  839. release_table(table);
  840. return -1;
  841. }
  842. ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", field->name, ast_str_buffer(escapebuf));
  843. first = 0;
  844. }
  845. release_table(table);
  846. ast_str_append(&sql, 0, "%s", ast_str_buffer(where));
  847. ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
  848. /* We now have our complete statement; Lets connect to the server and execute it. */
  849. if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
  850. ast_mutex_unlock(&pgsql_lock);
  851. return -1;
  852. }
  853. numrows = atoi(PQcmdTuples(result));
  854. ast_mutex_unlock(&pgsql_lock);
  855. ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
  856. /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
  857. * An integer greater than zero indicates the number of rows affected
  858. * Zero indicates that no records were updated
  859. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  860. */
  861. if (numrows >= 0) {
  862. return (int) numrows;
  863. }
  864. return -1;
  865. }
  866. static int store_pgsql(const char *database, const char *table, const struct ast_variable *fields)
  867. {
  868. RAII_VAR(PGresult *, result, NULL, PQclear);
  869. int numrows;
  870. struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
  871. struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
  872. struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
  873. int pgresult;
  874. const struct ast_variable *field = fields;
  875. /*
  876. * Ignore database from the extconfig.conf since it was
  877. * configured by res_pgsql.conf.
  878. */
  879. database = dbname;
  880. if (!table) {
  881. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  882. return -1;
  883. }
  884. /*
  885. * Must connect to the server before anything else as ESCAPE_STRING()
  886. * uses pgsqlConn
  887. */
  888. ast_mutex_lock(&pgsql_lock);
  889. if (!pgsql_reconnect(database)) {
  890. ast_mutex_unlock(&pgsql_lock);
  891. return -1;
  892. }
  893. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  894. if (!field) {
  895. ast_log(LOG_WARNING,
  896. "PostgreSQL RealTime: Realtime storage requires at least 1 parameter and 1 value to store.\n");
  897. if (pgsqlConn) {
  898. PQfinish(pgsqlConn);
  899. pgsqlConn = NULL;
  900. }
  901. ast_mutex_unlock(&pgsql_lock);
  902. return -1;
  903. }
  904. /* Create the first part of the query using the first parameter/value pairs we just extracted
  905. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  906. ESCAPE_STRING(buf, field->name);
  907. ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
  908. ESCAPE_STRING(buf, field->value);
  909. ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
  910. while ((field = field->next)) {
  911. ESCAPE_STRING(buf, field->name);
  912. ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
  913. ESCAPE_STRING(buf, field->value);
  914. ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
  915. }
  916. ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
  917. ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
  918. /* We now have our complete statement; Lets connect to the server and execute it. */
  919. if (pgsql_exec(database, table, ast_str_buffer(sql1), &result) != 0) {
  920. ast_mutex_unlock(&pgsql_lock);
  921. return -1;
  922. }
  923. numrows = atoi(PQcmdTuples(result));
  924. ast_mutex_unlock(&pgsql_lock);
  925. ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s.", table);
  926. /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
  927. * An integer greater than zero indicates the number of rows affected
  928. * Zero indicates that no records were updated
  929. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  930. */
  931. if (numrows >= 0) {
  932. return numrows;
  933. }
  934. return -1;
  935. }
  936. static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, const struct ast_variable *fields)
  937. {
  938. RAII_VAR(PGresult *, result, NULL, PQclear);
  939. int numrows = 0;
  940. int pgresult;
  941. struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
  942. struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
  943. const struct ast_variable *field;
  944. /*
  945. * Ignore database from the extconfig.conf since it was
  946. * configured by res_pgsql.conf.
  947. */
  948. database = dbname;
  949. if (!table) {
  950. ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
  951. return -1;
  952. }
  953. /*
  954. * Must connect to the server before anything else as ESCAPE_STRING()
  955. * uses pgsqlConn
  956. */
  957. ast_mutex_lock(&pgsql_lock);
  958. if (!pgsql_reconnect(database)) {
  959. ast_mutex_unlock(&pgsql_lock);
  960. return -1;
  961. }
  962. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  963. if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup)) {
  964. ast_log(LOG_WARNING,
  965. "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
  966. if (pgsqlConn) {
  967. PQfinish(pgsqlConn);
  968. pgsqlConn = NULL;
  969. }
  970. ast_mutex_unlock(&pgsql_lock);
  971. return -1;
  972. }
  973. /* Create the first part of the query using the first parameter/value pairs we just extracted
  974. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  975. ESCAPE_STRING(buf1, keyfield);
  976. ESCAPE_STRING(buf2, lookup);
  977. ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
  978. for (field = fields; field; field = field->next) {
  979. ESCAPE_STRING(buf1, field->name);
  980. ESCAPE_STRING(buf2, field->value);
  981. ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
  982. }
  983. ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
  984. /* We now have our complete statement; Lets connect to the server and execute it. */
  985. if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
  986. ast_mutex_unlock(&pgsql_lock);
  987. return -1;
  988. }
  989. numrows = atoi(PQcmdTuples(result));
  990. ast_mutex_unlock(&pgsql_lock);
  991. ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
  992. /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
  993. * An integer greater than zero indicates the number of rows affected
  994. * Zero indicates that no records were updated
  995. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  996. */
  997. if (numrows >= 0)
  998. return (int) numrows;
  999. return -1;
  1000. }
  1001. static struct ast_config *config_pgsql(const char *database, const char *table,
  1002. const char *file, struct ast_config *cfg,
  1003. struct ast_flags flags, const char *suggested_incl, const char *who_asked)
  1004. {
  1005. RAII_VAR(PGresult *, result, NULL, PQclear);
  1006. long num_rows;
  1007. struct ast_variable *new_v;
  1008. struct ast_category *cur_cat = NULL;
  1009. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  1010. char last[80];
  1011. int last_cat_metric = 0;
  1012. last[0] = '\0';
  1013. /*
  1014. * Ignore database from the extconfig.conf since it is
  1015. * configured by res_pgsql.conf.
  1016. */
  1017. database = dbname;
  1018. if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
  1019. ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
  1020. return NULL;
  1021. }
  1022. ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
  1023. "WHERE filename='%s' and commented=0 "
  1024. "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
  1025. ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
  1026. ast_mutex_lock(&pgsql_lock);
  1027. /* We now have our complete statement; Lets connect to the server and execute it. */
  1028. if (pgsql_exec(database, table, ast_str_buffer(sql), &result) != 0) {
  1029. ast_mutex_unlock(&pgsql_lock);
  1030. return NULL;
  1031. }
  1032. if ((num_rows = PQntuples(result)) > 0) {
  1033. int rowIndex = 0;
  1034. ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
  1035. for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
  1036. char *field_category = PQgetvalue(result, rowIndex, 0);
  1037. char *field_var_name = PQgetvalue(result, rowIndex, 1);
  1038. char *field_var_val = PQgetvalue(result, rowIndex, 2);
  1039. char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
  1040. if (!strcmp(field_var_name, "#include")) {
  1041. if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
  1042. ast_mutex_unlock(&pgsql_lock);
  1043. return NULL;
  1044. }
  1045. continue;
  1046. }
  1047. if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
  1048. cur_cat = ast_category_new_dynamic(field_category);
  1049. if (!cur_cat) {
  1050. break;
  1051. }
  1052. ast_copy_string(last, field_category, sizeof(last));
  1053. last_cat_metric = atoi(field_cat_metric);
  1054. ast_category_append(cfg, cur_cat);
  1055. }
  1056. new_v = ast_variable_new(field_var_name, field_var_val, "");
  1057. ast_variable_append(cur_cat, new_v);
  1058. }
  1059. } else {
  1060. ast_log(LOG_WARNING,
  1061. "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
  1062. }
  1063. ast_mutex_unlock(&pgsql_lock);
  1064. return cfg;
  1065. }
  1066. static int require_pgsql(const char *database, const char *tablename, va_list ap)
  1067. {
  1068. struct columns *column;
  1069. struct tables *table;
  1070. char *elm;
  1071. int type, res = 0;
  1072. unsigned int size;
  1073. /*
  1074. * Ignore database from the extconfig.conf since it was
  1075. * configured by res_pgsql.conf.
  1076. */
  1077. database = dbname;
  1078. table = find_table(database, tablename);
  1079. if (!table) {
  1080. ast_log(LOG_WARNING, "Table %s not found in database. This table should exist if you're using realtime.\n", tablename);
  1081. return -1;
  1082. }
  1083. while ((elm = va_arg(ap, char *))) {
  1084. type = va_arg(ap, require_type);
  1085. size = va_arg(ap, unsigned int);
  1086. AST_LIST_TRAVERSE(&table->columns, column, list) {
  1087. if (strcmp(column->name, elm) == 0) {
  1088. /* Char can hold anything, as long as it is large enough */
  1089. if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
  1090. if ((size > column->len) && column->len != -1) {
  1091. ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
  1092. res = -1;
  1093. }
  1094. } else if (strncmp(column->type, "int", 3) == 0) {
  1095. int typesize = atoi(column->type + 3);
  1096. /* Integers can hold only other integers */
  1097. if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
  1098. type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
  1099. type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
  1100. type == RQ_UINTEGER2) && typesize == 2) {
  1101. ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
  1102. res = -1;
  1103. } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
  1104. type == RQ_UINTEGER4) && typesize == 4) {
  1105. ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
  1106. res = -1;
  1107. } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
  1108. ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
  1109. column->name,
  1110. type == RQ_CHAR ? "char" :
  1111. type == RQ_DATETIME ? "datetime" :
  1112. type == RQ_DATE ? "date" :
  1113. type == RQ_FLOAT ? "float" :
  1114. "a rather stiff drink ",
  1115. size, column->type);
  1116. res = -1;
  1117. }
  1118. } else if (strncmp(column->type, "float", 5) == 0) {
  1119. if (!ast_rq_is_int(type) && type != RQ_FLOAT) {
  1120. ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
  1121. res = -1;
  1122. }
  1123. } else if (strncmp(column->type, "timestamp", 9) == 0) {
  1124. if (type != RQ_DATETIME && type != RQ_DATE) {
  1125. ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
  1126. res = -1;
  1127. }
  1128. } else { /* There are other types that no module implements yet */
  1129. ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
  1130. res = -1;
  1131. }
  1132. break;
  1133. }
  1134. }
  1135. if (!column) {
  1136. if (requirements == RQ_WARN) {
  1137. ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
  1138. res = -1;
  1139. } else {
  1140. struct ast_str *sql = ast_str_create(100);
  1141. char fieldtype[10];
  1142. PGresult *result;
  1143. if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
  1144. /* Size is minimum length; make it at least 50% greater,
  1145. * just to be sure, because PostgreSQL doesn't support
  1146. * resizing columns. */
  1147. snprintf(fieldtype, sizeof(fieldtype), "CHAR(%u)",
  1148. size < 15 ? size * 2 :
  1149. (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
  1150. } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
  1151. snprintf(fieldtype, sizeof(fieldtype), "INT2");
  1152. } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
  1153. snprintf(fieldtype, sizeof(fieldtype), "INT4");
  1154. } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
  1155. snprintf(fieldtype, sizeof(fieldtype), "INT8");
  1156. } else if (type == RQ_UINTEGER8) {
  1157. /* No such type on PostgreSQL */
  1158. snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
  1159. } else if (type == RQ_FLOAT) {
  1160. snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
  1161. } else if (type == RQ_DATE) {
  1162. snprintf(fieldtype, sizeof(fieldtype), "DATE");
  1163. } else if (type == RQ_DATETIME) {
  1164. snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
  1165. } else {
  1166. ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
  1167. ast_free(sql);
  1168. continue;
  1169. }
  1170. ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
  1171. ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
  1172. ast_mutex_lock(&pgsql_lock);
  1173. ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
  1174. if (pgsql_exec(database, tablename, ast_str_buffer(sql), &result) != 0) {
  1175. ast_mutex_unlock(&pgsql_lock);
  1176. release_table(table);
  1177. return -1;
  1178. }
  1179. ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
  1180. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  1181. ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
  1182. }
  1183. PQclear(result);
  1184. ast_mutex_unlock(&pgsql_lock);
  1185. ast_free(sql);
  1186. }
  1187. }
  1188. }
  1189. release_table(table);
  1190. return res;
  1191. }
  1192. static int unload_pgsql(const char *database, const char *tablename)
  1193. {
  1194. struct tables *cur;
  1195. /*
  1196. * Ignore database from the extconfig.conf since it was
  1197. * configured by res_pgsql.conf.
  1198. */
  1199. database = dbname;
  1200. ast_debug(2, "About to lock table cache list\n");
  1201. AST_LIST_LOCK(&psql_tables);
  1202. ast_debug(2, "About to traverse table cache list\n");
  1203. AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
  1204. if (strcmp(cur->name, tablename) == 0) {
  1205. ast_debug(2, "About to remove matching cache entry\n");
  1206. AST_LIST_REMOVE_CURRENT(list);
  1207. ast_debug(2, "About to destroy matching cache entry\n");
  1208. destroy_table(cur);
  1209. ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
  1210. break;
  1211. }
  1212. }
  1213. AST_LIST_TRAVERSE_SAFE_END
  1214. AST_LIST_UNLOCK(&psql_tables);
  1215. ast_debug(2, "About to return\n");
  1216. return cur ? 0 : -1;
  1217. }
  1218. static struct ast_config_engine pgsql_engine = {
  1219. .name = "pgsql",
  1220. .load_func = config_pgsql,
  1221. .realtime_func = realtime_pgsql,
  1222. .realtime_multi_func = realtime_multi_pgsql,
  1223. .store_func = store_pgsql,
  1224. .destroy_func = destroy_pgsql,
  1225. .update_func = update_pgsql,
  1226. .update2_func = update2_pgsql,
  1227. .require_func = require_pgsql,
  1228. .unload_func = unload_pgsql,
  1229. };
  1230. static int load_module(void)
  1231. {
  1232. if(!parse_config(0))
  1233. return AST_MODULE_LOAD_DECLINE;
  1234. ast_config_engine_register(&pgsql_engine);
  1235. ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
  1236. return 0;
  1237. }
  1238. static int unload_module(void)
  1239. {
  1240. struct tables *table;
  1241. /* Acquire control before doing anything to the module itself. */
  1242. ast_mutex_lock(&pgsql_lock);
  1243. if (pgsqlConn) {
  1244. PQfinish(pgsqlConn);
  1245. pgsqlConn = NULL;
  1246. }
  1247. ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
  1248. ast_config_engine_deregister(&pgsql_engine);
  1249. /* Unlock so something else can destroy the lock. */
  1250. ast_mutex_unlock(&pgsql_lock);
  1251. /* Destroy cached table info */
  1252. AST_LIST_LOCK(&psql_tables);
  1253. while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
  1254. destroy_table(table);
  1255. }
  1256. AST_LIST_UNLOCK(&psql_tables);
  1257. return 0;
  1258. }
  1259. static int reload(void)
  1260. {
  1261. parse_config(1);
  1262. return 0;
  1263. }
  1264. static int parse_config(int is_reload)
  1265. {
  1266. struct ast_config *config;
  1267. const char *s;
  1268. struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  1269. config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
  1270. if (config == CONFIG_STATUS_FILEUNCHANGED) {
  1271. return 0;
  1272. }
  1273. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  1274. ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
  1275. return 0;
  1276. }
  1277. ast_mutex_lock(&pgsql_lock);
  1278. /* XXX: Why would we do this before we're ready to establish a new connection? */
  1279. if (pgsqlConn) {
  1280. PQfinish(pgsqlConn);
  1281. pgsqlConn = NULL;
  1282. }
  1283. if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
  1284. ast_log(LOG_WARNING,
  1285. "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
  1286. strcpy(dbuser, "asterisk");
  1287. } else {
  1288. ast_copy_string(dbuser, s, sizeof(dbuser));
  1289. }
  1290. if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
  1291. ast_log(LOG_WARNING,
  1292. "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
  1293. strcpy(dbpass, "asterisk");
  1294. } else {
  1295. ast_copy_string(dbpass, s, sizeof(dbpass));
  1296. }
  1297. if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
  1298. ast_log(LOG_WARNING,
  1299. "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
  1300. dbhost[0] = '\0';
  1301. } else {
  1302. ast_copy_string(dbhost, s, sizeof(dbhost));
  1303. }
  1304. if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
  1305. ast_log(LOG_WARNING,
  1306. "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
  1307. strcpy(dbname, "asterisk");
  1308. } else {
  1309. ast_copy_string(dbname, s, sizeof(dbname));
  1310. }
  1311. if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
  1312. ast_log(LOG_WARNING,
  1313. "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
  1314. dbport = 5432;
  1315. } else {
  1316. dbport = atoi(s);
  1317. }
  1318. if (!(s = ast_variable_retrieve(config, "general", "dbappname"))) {
  1319. dbappname[0] = '\0';
  1320. } else {
  1321. ast_copy_string(dbappname, s, sizeof(dbappname));
  1322. }
  1323. if (!ast_strlen_zero(dbhost)) {
  1324. /* No socket needed */
  1325. } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
  1326. ast_log(LOG_WARNING,
  1327. "PostgreSQL RealTime: No database socket found, using '/tmp/.s.PGSQL.%d' as default.\n", dbport);
  1328. strcpy(dbsock, "/tmp");
  1329. } else {
  1330. ast_copy_string(dbsock, s, sizeof(dbsock));
  1331. }
  1332. if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
  1333. ast_log(LOG_WARNING,
  1334. "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
  1335. requirements = RQ_WARN;
  1336. } else if (!strcasecmp(s, "createclose")) {
  1337. requirements = RQ_CREATECLOSE;
  1338. } else if (!strcasecmp(s, "createchar")) {
  1339. requirements = RQ_CREATECHAR;
  1340. }
  1341. ast_config_destroy(config);
  1342. if (DEBUG_ATLEAST(1)) {
  1343. if (!ast_strlen_zero(dbhost)) {
  1344. ast_log(LOG_DEBUG, "PostgreSQL RealTime Host: %s\n", dbhost);
  1345. ast_log(LOG_DEBUG, "PostgreSQL RealTime Port: %i\n", dbport);
  1346. } else {
  1347. ast_log(LOG_DEBUG, "PostgreSQL RealTime Socket: %s\n", dbsock);
  1348. }
  1349. ast_log(LOG_DEBUG, "PostgreSQL RealTime User: %s\n", dbuser);
  1350. ast_log(LOG_DEBUG, "PostgreSQL RealTime Password: %s\n", dbpass);
  1351. ast_log(LOG_DEBUG, "PostgreSQL RealTime DBName: %s\n", dbname);
  1352. }
  1353. if (!pgsql_reconnect(NULL)) {
  1354. ast_log(LOG_WARNING,
  1355. "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
  1356. ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
  1357. }
  1358. ast_verb(2, "PostgreSQL RealTime reloaded.\n");
  1359. /* Done reloading. Release lock so others can now use driver. */
  1360. ast_mutex_unlock(&pgsql_lock);
  1361. return 1;
  1362. }
  1363. static int pgsql_reconnect(const char *database)
  1364. {
  1365. char my_database[50];
  1366. ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
  1367. /* mutex lock should have been locked before calling this function. */
  1368. if (pgsqlConn) {
  1369. if (PQstatus(pgsqlConn) == CONNECTION_OK) {
  1370. /* We're good? */
  1371. return 1;
  1372. }
  1373. PQfinish(pgsqlConn);
  1374. pgsqlConn = NULL;
  1375. }
  1376. /* DB password can legitimately be 0-length */
  1377. if ((!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
  1378. struct ast_str *conn_info = ast_str_create(128);
  1379. if (!conn_info) {
  1380. ast_log(LOG_ERROR, "PostgreSQL RealTime: Failed to allocate memory for connection string.\n");
  1381. return 0;
  1382. }
  1383. ast_str_set(&conn_info, 0, "host=%s port=%d dbname=%s user=%s",
  1384. S_OR(dbhost, dbsock), dbport, my_database, dbuser);
  1385. if (!ast_strlen_zero(dbappname)) {
  1386. ast_str_append(&conn_info, 0, " application_name=%s", dbappname);
  1387. }
  1388. if (!ast_strlen_zero(dbpass)) {
  1389. ast_str_append(&conn_info, 0, " password=%s", dbpass);
  1390. }
  1391. pgsqlConn = PQconnectdb(ast_str_buffer(conn_info));
  1392. ast_free(conn_info);
  1393. conn_info = NULL;
  1394. ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
  1395. if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
  1396. ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
  1397. connect_time = time(NULL);
  1398. version = PQserverVersion(pgsqlConn);
  1399. return 1;
  1400. } else {
  1401. ast_log(LOG_ERROR,
  1402. "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
  1403. my_database, dbhost, PQresultErrorMessage(NULL));
  1404. return 0;
  1405. }
  1406. } else {
  1407. ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
  1408. return 1;
  1409. }
  1410. }
  1411. static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1412. {
  1413. struct tables *cur;
  1414. int l, which;
  1415. char *ret = NULL;
  1416. switch (cmd) {
  1417. case CLI_INIT:
  1418. e->command = "realtime show pgsql cache";
  1419. e->usage =
  1420. "Usage: realtime show pgsql cache [<table>]\n"
  1421. " Shows table cache for the PostgreSQL RealTime driver\n";
  1422. return NULL;
  1423. case CLI_GENERATE:
  1424. if (a->argc != 4) {
  1425. return NULL;
  1426. }
  1427. l = strlen(a->word);
  1428. which = 0;
  1429. AST_LIST_LOCK(&psql_tables);
  1430. AST_LIST_TRAVERSE(&psql_tables, cur, list) {
  1431. if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
  1432. ret = ast_strdup(cur->name);
  1433. break;
  1434. }
  1435. }
  1436. AST_LIST_UNLOCK(&psql_tables);
  1437. return ret;
  1438. }
  1439. if (a->argc == 4) {
  1440. /* List of tables */
  1441. AST_LIST_LOCK(&psql_tables);
  1442. AST_LIST_TRAVERSE(&psql_tables, cur, list) {
  1443. ast_cli(a->fd, "%s\n", cur->name);
  1444. }
  1445. AST_LIST_UNLOCK(&psql_tables);
  1446. } else if (a->argc == 5) {
  1447. /* List of columns */
  1448. if ((cur = find_table(NULL, a->argv[4]))) {
  1449. struct columns *col;
  1450. ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
  1451. ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
  1452. AST_LIST_TRAVERSE(&cur->columns, col, list) {
  1453. ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
  1454. }
  1455. release_table(cur);
  1456. } else {
  1457. ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
  1458. }
  1459. }
  1460. return 0;
  1461. }
  1462. static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1463. {
  1464. char status[256], credentials[100] = "";
  1465. int is_connected = 0, ctimesec = time(NULL) - connect_time;
  1466. switch (cmd) {
  1467. case CLI_INIT:
  1468. e->command = "realtime show pgsql status";
  1469. e->usage =
  1470. "Usage: realtime show pgsql status\n"
  1471. " Shows connection information for the PostgreSQL RealTime driver\n";
  1472. return NULL;
  1473. case CLI_GENERATE:
  1474. return NULL;
  1475. }
  1476. if (a->argc != 4)
  1477. return CLI_SHOWUSAGE;
  1478. ast_mutex_lock(&pgsql_lock);
  1479. is_connected = (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK);
  1480. ast_mutex_unlock(&pgsql_lock);
  1481. if (is_connected) {
  1482. if (!ast_strlen_zero(dbhost))
  1483. snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
  1484. else if (!ast_strlen_zero(dbsock))
  1485. snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
  1486. else
  1487. snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
  1488. if (!ast_strlen_zero(dbuser))
  1489. snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
  1490. if (ctimesec > 31536000)
  1491. ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
  1492. status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
  1493. (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
  1494. else if (ctimesec > 86400)
  1495. ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
  1496. credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
  1497. ctimesec % 60);
  1498. else if (ctimesec > 3600)
  1499. ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
  1500. ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
  1501. else if (ctimesec > 60)
  1502. ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
  1503. ctimesec % 60);
  1504. else
  1505. ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
  1506. return CLI_SUCCESS;
  1507. } else {
  1508. return CLI_FAILURE;
  1509. }
  1510. }
  1511. /* needs usecount semantics defined */
  1512. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL RealTime Configuration Driver",
  1513. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  1514. .load = load_module,
  1515. .unload = unload_module,
  1516. .reload = reload,
  1517. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  1518. );