res_config_pgsql.c 52 KB

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