res_config_pgsql.c 54 KB

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