res_config_pgsql.c 52 KB

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