cdr_pgsql.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2003 - 2012
  5. *
  6. * Matthew D. Hardeman <mhardemn@papersoft.com>
  7. * Adapted from the MySQL CDR logger originally by James Sharp
  8. *
  9. * Modified September 2003
  10. * Matthew D. Hardeman <mhardemn@papersoft.com>
  11. *
  12. * See http://www.asterisk.org for more information about
  13. * the Asterisk project. Please do not directly contact
  14. * any of the maintainers of this project for assistance;
  15. * the project provides a web site, mailing lists and IRC
  16. * channels for your use.
  17. *
  18. * This program is free software, distributed under the terms of
  19. * the GNU General Public License Version 2. See the LICENSE file
  20. * at the top of the source tree.
  21. */
  22. /*!
  23. * \file
  24. * \brief PostgreSQL CDR logger
  25. *
  26. * \author Matthew D. Hardeman <mhardemn@papersoft.com>
  27. * PostgreSQL http://www.postgresql.org/
  28. *
  29. * See also
  30. * \arg \ref Config_cdr
  31. * PostgreSQL http://www.postgresql.org/
  32. * \ingroup cdr_drivers
  33. */
  34. /*! \li \ref cdr_pgsql.c uses the configuration file \ref cdr_pgsql.conf
  35. * \addtogroup configuration_file Configuration Files
  36. */
  37. /*!
  38. * \page cdr_pgsql.conf cdr_pgsql.conf
  39. * \verbinclude cdr_pgsql.conf.sample
  40. */
  41. /*** MODULEINFO
  42. <depend>pgsql</depend>
  43. <support_level>extended</support_level>
  44. ***/
  45. #include "asterisk.h"
  46. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  47. #include <libpq-fe.h>
  48. #include "asterisk/config.h"
  49. #include "asterisk/channel.h"
  50. #include "asterisk/cdr.h"
  51. #include "asterisk/cli.h"
  52. #include "asterisk/module.h"
  53. #define DATE_FORMAT "'%Y-%m-%d %T'"
  54. static const char name[] = "pgsql";
  55. static const char config[] = "cdr_pgsql.conf";
  56. static char *pghostname;
  57. static char *pgdbname;
  58. static char *pgdbuser;
  59. static char *pgpassword;
  60. static char *pgappname;
  61. static char *pgdbport;
  62. static char *table;
  63. static char *encoding;
  64. static char *tz;
  65. static int connected = 0;
  66. static int maxsize = 512, maxsize2 = 512;
  67. static time_t connect_time = 0;
  68. static int totalrecords = 0;
  69. static int records;
  70. static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  71. static struct ast_cli_entry cdr_pgsql_status_cli[] = {
  72. AST_CLI_DEFINE(handle_cdr_pgsql_status, "Show connection status of the PostgreSQL CDR driver (cdr_pgsql)"),
  73. };
  74. AST_MUTEX_DEFINE_STATIC(pgsql_lock);
  75. static PGconn *conn = NULL;
  76. struct columns {
  77. char *name;
  78. char *type;
  79. int len;
  80. unsigned int notnull:1;
  81. unsigned int hasdefault:1;
  82. AST_RWLIST_ENTRY(columns) list;
  83. };
  84. static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
  85. #define LENGTHEN_BUF1(size) \
  86. do { \
  87. /* Lengthen buffer, if necessary */ \
  88. if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
  89. if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) { \
  90. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  91. ast_free(sql); \
  92. ast_free(sql2); \
  93. AST_RWLIST_UNLOCK(&psql_columns); \
  94. ast_mutex_unlock(&pgsql_lock); \
  95. return -1; \
  96. } \
  97. } \
  98. } while (0)
  99. #define LENGTHEN_BUF2(size) \
  100. do { \
  101. if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
  102. if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
  103. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  104. ast_free(sql); \
  105. ast_free(sql2); \
  106. AST_RWLIST_UNLOCK(&psql_columns); \
  107. ast_mutex_unlock(&pgsql_lock); \
  108. return -1; \
  109. } \
  110. } \
  111. } while (0)
  112. /*! \brief Handle the CLI command cdr show pgsql status */
  113. static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  114. {
  115. switch (cmd) {
  116. case CLI_INIT:
  117. e->command = "cdr show pgsql status";
  118. e->usage =
  119. "Usage: cdr show pgsql status\n"
  120. " Shows current connection status for cdr_pgsql\n";
  121. return NULL;
  122. case CLI_GENERATE:
  123. return NULL;
  124. }
  125. if (a->argc != 3)
  126. return CLI_SHOWUSAGE;
  127. if (connected) {
  128. char status[256], status2[100] = "";
  129. int ctime = time(NULL) - connect_time;
  130. if (pgdbport) {
  131. snprintf(status, 255, "Connected to %s@%s, port %s", pgdbname, pghostname, pgdbport);
  132. } else {
  133. snprintf(status, 255, "Connected to %s@%s", pgdbname, pghostname);
  134. }
  135. if (pgdbuser && *pgdbuser) {
  136. snprintf(status2, 99, " with username %s", pgdbuser);
  137. }
  138. if (table && *table) {
  139. snprintf(status2, 99, " using table %s", table);
  140. }
  141. if (ctime > 31536000) {
  142. ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 31536000, (ctime % 31536000) / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
  143. } else if (ctime > 86400) {
  144. ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
  145. } else if (ctime > 3600) {
  146. ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 3600, (ctime % 3600) / 60, ctime % 60);
  147. } else if (ctime > 60) {
  148. ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60, ctime % 60);
  149. } else {
  150. ast_cli(a->fd, "%s%s for %d seconds.\n", status, status2, ctime);
  151. }
  152. if (records == totalrecords) {
  153. ast_cli(a->fd, " Wrote %d records since last restart.\n", totalrecords);
  154. } else {
  155. ast_cli(a->fd, " Wrote %d records since last restart and %d records since last reconnect.\n", totalrecords, records);
  156. }
  157. } else {
  158. ast_cli(a->fd, "Not currently connected to a PgSQL server.\n");
  159. }
  160. return CLI_SUCCESS;
  161. }
  162. static void pgsql_reconnect(void)
  163. {
  164. struct ast_str *conn_info = ast_str_create(128);
  165. if (!conn_info) {
  166. ast_log(LOG_ERROR, "Failed to allocate memory for connection string.\n");
  167. return;
  168. }
  169. if (conn) {
  170. PQfinish(conn);
  171. conn = NULL;
  172. }
  173. ast_str_set(&conn_info, 0, "host=%s port=%s dbname=%s user=%s",
  174. pghostname, pgdbport, pgdbname, pgdbuser);
  175. if (!ast_strlen_zero(pgappname)) {
  176. ast_str_append(&conn_info, 0, " application_name=%s", pgappname);
  177. }
  178. if (!ast_strlen_zero(pgpassword)) {
  179. ast_str_append(&conn_info, 0, " password=%s", pgpassword);
  180. }
  181. conn = PQconnectdb(ast_str_buffer(conn_info));
  182. ast_free(conn_info);
  183. }
  184. static int pgsql_log(struct ast_cdr *cdr)
  185. {
  186. struct ast_tm tm;
  187. char *pgerror;
  188. PGresult *result;
  189. ast_mutex_lock(&pgsql_lock);
  190. if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
  191. pgsql_reconnect();
  192. if (PQstatus(conn) != CONNECTION_BAD) {
  193. connected = 1;
  194. connect_time = time(NULL);
  195. records = 0;
  196. if (PQsetClientEncoding(conn, encoding)) {
  197. #ifdef HAVE_PGSQL_pg_encoding_to_char
  198. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  199. #else
  200. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  201. #endif
  202. }
  203. } else {
  204. pgerror = PQerrorMessage(conn);
  205. ast_log(LOG_ERROR, "Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
  206. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  207. PQfinish(conn);
  208. conn = NULL;
  209. }
  210. }
  211. if (connected) {
  212. struct columns *cur;
  213. struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
  214. char buf[257], escapebuf[513], *value;
  215. int first = 1;
  216. if (!sql || !sql2) {
  217. ast_free(sql);
  218. ast_free(sql2);
  219. return -1;
  220. }
  221. ast_str_set(&sql, 0, "INSERT INTO %s (", table);
  222. ast_str_set(&sql2, 0, " VALUES (");
  223. AST_RWLIST_RDLOCK(&psql_columns);
  224. AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
  225. /* For fields not set, simply skip them */
  226. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  227. if (strcmp(cur->name, "calldate") == 0 && !value) {
  228. ast_cdr_format_var(cdr, "start", &value, buf, sizeof(buf), 0);
  229. }
  230. if (!value) {
  231. if (cur->notnull && !cur->hasdefault) {
  232. /* Field is NOT NULL (but no default), must include it anyway */
  233. LENGTHEN_BUF1(strlen(cur->name) + 2);
  234. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  235. LENGTHEN_BUF2(3);
  236. ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
  237. first = 0;
  238. }
  239. continue;
  240. }
  241. LENGTHEN_BUF1(strlen(cur->name) + 2);
  242. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  243. if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
  244. if (strncmp(cur->type, "int", 3) == 0) {
  245. LENGTHEN_BUF2(13);
  246. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
  247. } else if (strncmp(cur->type, "float", 5) == 0) {
  248. LENGTHEN_BUF2(31);
  249. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
  250. } else {
  251. /* char, hopefully */
  252. LENGTHEN_BUF2(31);
  253. ast_localtime(&cdr->start, &tm, tz);
  254. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  255. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  256. }
  257. } else if (strcmp(cur->name, "answer") == 0) {
  258. if (strncmp(cur->type, "int", 3) == 0) {
  259. LENGTHEN_BUF2(13);
  260. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
  261. } else if (strncmp(cur->type, "float", 5) == 0) {
  262. LENGTHEN_BUF2(31);
  263. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
  264. } else {
  265. /* char, hopefully */
  266. LENGTHEN_BUF2(31);
  267. ast_localtime(&cdr->answer, &tm, tz);
  268. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  269. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  270. }
  271. } else if (strcmp(cur->name, "end") == 0) {
  272. if (strncmp(cur->type, "int", 3) == 0) {
  273. LENGTHEN_BUF2(13);
  274. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
  275. } else if (strncmp(cur->type, "float", 5) == 0) {
  276. LENGTHEN_BUF2(31);
  277. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
  278. } else {
  279. /* char, hopefully */
  280. LENGTHEN_BUF2(31);
  281. ast_localtime(&cdr->end, &tm, tz);
  282. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  283. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  284. }
  285. } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
  286. if (cur->type[0] == 'i') {
  287. /* Get integer, no need to escape anything */
  288. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  289. LENGTHEN_BUF2(13);
  290. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  291. } else if (strncmp(cur->type, "float", 5) == 0) {
  292. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  293. LENGTHEN_BUF2(31);
  294. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  295. } else {
  296. /* Char field, probably */
  297. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  298. LENGTHEN_BUF2(31);
  299. ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  300. }
  301. } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
  302. if (strncmp(cur->type, "int", 3) == 0) {
  303. /* Integer, no need to escape anything */
  304. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 1);
  305. LENGTHEN_BUF2(13);
  306. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  307. } else {
  308. /* Although this is a char field, there are no special characters in the values for these fields */
  309. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  310. LENGTHEN_BUF2(31);
  311. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
  312. }
  313. } else {
  314. /* Arbitrary field, could be anything */
  315. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  316. if (strncmp(cur->type, "int", 3) == 0) {
  317. long long whatever;
  318. if (value && sscanf(value, "%30lld", &whatever) == 1) {
  319. LENGTHEN_BUF2(26);
  320. ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
  321. } else {
  322. LENGTHEN_BUF2(2);
  323. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  324. }
  325. } else if (strncmp(cur->type, "float", 5) == 0) {
  326. long double whatever;
  327. if (value && sscanf(value, "%30Lf", &whatever) == 1) {
  328. LENGTHEN_BUF2(51);
  329. ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
  330. } else {
  331. LENGTHEN_BUF2(2);
  332. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  333. }
  334. /* XXX Might want to handle dates, times, and other misc fields here XXX */
  335. } else {
  336. if (value)
  337. PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
  338. else
  339. escapebuf[0] = '\0';
  340. LENGTHEN_BUF2(strlen(escapebuf) + 3);
  341. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
  342. }
  343. }
  344. first = 0;
  345. }
  346. LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
  347. AST_RWLIST_UNLOCK(&psql_columns);
  348. ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
  349. ast_debug(3, "Inserting a CDR record: [%s]\n", ast_str_buffer(sql));
  350. /* Test to be sure we're still connected... */
  351. /* If we're connected, and connection is working, good. */
  352. /* Otherwise, attempt reconnect. If it fails... sorry... */
  353. if (PQstatus(conn) == CONNECTION_OK) {
  354. connected = 1;
  355. } else {
  356. ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
  357. PQreset(conn);
  358. if (PQstatus(conn) == CONNECTION_OK) {
  359. ast_log(LOG_ERROR, "Connection reestablished.\n");
  360. connected = 1;
  361. connect_time = time(NULL);
  362. records = 0;
  363. } else {
  364. pgerror = PQerrorMessage(conn);
  365. ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
  366. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  367. PQfinish(conn);
  368. conn = NULL;
  369. connected = 0;
  370. ast_mutex_unlock(&pgsql_lock);
  371. ast_free(sql);
  372. ast_free(sql2);
  373. return -1;
  374. }
  375. }
  376. result = PQexec(conn, ast_str_buffer(sql));
  377. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  378. pgerror = PQresultErrorMessage(result);
  379. ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
  380. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  381. ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
  382. PQreset(conn);
  383. if (PQstatus(conn) == CONNECTION_OK) {
  384. ast_log(LOG_ERROR, "Connection reestablished.\n");
  385. connected = 1;
  386. connect_time = time(NULL);
  387. records = 0;
  388. PQclear(result);
  389. result = PQexec(conn, ast_str_buffer(sql));
  390. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  391. pgerror = PQresultErrorMessage(result);
  392. ast_log(LOG_ERROR, "HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
  393. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  394. } else {
  395. /* Second try worked out ok */
  396. totalrecords++;
  397. records++;
  398. ast_mutex_unlock(&pgsql_lock);
  399. PQclear(result);
  400. return 0;
  401. }
  402. }
  403. ast_mutex_unlock(&pgsql_lock);
  404. PQclear(result);
  405. ast_free(sql);
  406. ast_free(sql2);
  407. return -1;
  408. } else {
  409. totalrecords++;
  410. records++;
  411. }
  412. PQclear(result);
  413. ast_free(sql);
  414. ast_free(sql2);
  415. }
  416. ast_mutex_unlock(&pgsql_lock);
  417. return 0;
  418. }
  419. /* This function should be called without holding the pgsql_columns lock */
  420. static void empty_columns(void)
  421. {
  422. struct columns *current;
  423. AST_RWLIST_WRLOCK(&psql_columns);
  424. while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
  425. ast_free(current);
  426. }
  427. AST_RWLIST_UNLOCK(&psql_columns);
  428. }
  429. static int unload_module(void)
  430. {
  431. if (ast_cdr_unregister(name)) {
  432. return -1;
  433. }
  434. ast_cli_unregister_multiple(cdr_pgsql_status_cli, ARRAY_LEN(cdr_pgsql_status_cli));
  435. if (conn) {
  436. PQfinish(conn);
  437. conn = NULL;
  438. }
  439. ast_free(pghostname);
  440. ast_free(pgdbname);
  441. ast_free(pgdbuser);
  442. ast_free(pgpassword);
  443. ast_free(pgappname);
  444. ast_free(pgdbport);
  445. ast_free(table);
  446. ast_free(encoding);
  447. ast_free(tz);
  448. empty_columns();
  449. return 0;
  450. }
  451. static int config_module(int reload)
  452. {
  453. char *pgerror;
  454. struct columns *cur;
  455. PGresult *result;
  456. const char *tmp;
  457. struct ast_config *cfg;
  458. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  459. if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
  460. ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
  461. return -1;
  462. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  463. return 0;
  464. }
  465. ast_mutex_lock(&pgsql_lock);
  466. if (!ast_variable_browse(cfg, "global")) {
  467. ast_config_destroy(cfg);
  468. ast_mutex_unlock(&pgsql_lock);
  469. ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
  470. reload ? "reload" : "load");
  471. return -1;
  472. }
  473. if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
  474. ast_log(LOG_WARNING, "PostgreSQL server hostname not specified. Assuming unix socket connection\n");
  475. tmp = ""; /* connect via UNIX-socket by default */
  476. }
  477. ast_free(pghostname);
  478. if (!(pghostname = ast_strdup(tmp))) {
  479. ast_config_destroy(cfg);
  480. ast_mutex_unlock(&pgsql_lock);
  481. return -1;
  482. }
  483. if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
  484. ast_log(LOG_WARNING, "PostgreSQL database not specified. Assuming asterisk\n");
  485. tmp = "asteriskcdrdb";
  486. }
  487. ast_free(pgdbname);
  488. if (!(pgdbname = ast_strdup(tmp))) {
  489. ast_config_destroy(cfg);
  490. ast_mutex_unlock(&pgsql_lock);
  491. return -1;
  492. }
  493. if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
  494. ast_log(LOG_WARNING, "PostgreSQL database user not specified. Assuming asterisk\n");
  495. tmp = "asterisk";
  496. }
  497. ast_free(pgdbuser);
  498. if (!(pgdbuser = ast_strdup(tmp))) {
  499. ast_config_destroy(cfg);
  500. ast_mutex_unlock(&pgsql_lock);
  501. return -1;
  502. }
  503. if (!(tmp = ast_variable_retrieve(cfg, "global", "appname"))) {
  504. tmp = "";
  505. }
  506. ast_free(pgappname);
  507. if (!(pgappname = ast_strdup(tmp))) {
  508. ast_config_destroy(cfg);
  509. ast_mutex_unlock(&pgsql_lock);
  510. return -1;
  511. }
  512. if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
  513. ast_log(LOG_WARNING, "PostgreSQL database password not specified. Assuming blank\n");
  514. tmp = "";
  515. }
  516. ast_free(pgpassword);
  517. if (!(pgpassword = ast_strdup(tmp))) {
  518. ast_config_destroy(cfg);
  519. ast_mutex_unlock(&pgsql_lock);
  520. return -1;
  521. }
  522. if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
  523. ast_log(LOG_WARNING, "PostgreSQL database port not specified. Using default 5432.\n");
  524. tmp = "5432";
  525. }
  526. ast_free(pgdbport);
  527. if (!(pgdbport = ast_strdup(tmp))) {
  528. ast_config_destroy(cfg);
  529. ast_mutex_unlock(&pgsql_lock);
  530. return -1;
  531. }
  532. if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
  533. ast_log(LOG_WARNING, "CDR table not specified. Assuming cdr\n");
  534. tmp = "cdr";
  535. }
  536. ast_free(table);
  537. if (!(table = ast_strdup(tmp))) {
  538. ast_config_destroy(cfg);
  539. ast_mutex_unlock(&pgsql_lock);
  540. return -1;
  541. }
  542. if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
  543. ast_log(LOG_WARNING, "Encoding not specified. Assuming LATIN9\n");
  544. tmp = "LATIN9";
  545. }
  546. ast_free(encoding);
  547. if (!(encoding = ast_strdup(tmp))) {
  548. ast_config_destroy(cfg);
  549. ast_mutex_unlock(&pgsql_lock);
  550. return -1;
  551. }
  552. if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
  553. tmp = "";
  554. }
  555. ast_free(tz);
  556. tz = NULL;
  557. if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
  558. ast_config_destroy(cfg);
  559. ast_mutex_unlock(&pgsql_lock);
  560. return -1;
  561. }
  562. if (option_debug) {
  563. if (ast_strlen_zero(pghostname)) {
  564. ast_debug(1, "using default unix socket\n");
  565. } else {
  566. ast_debug(1, "got hostname of %s\n", pghostname);
  567. }
  568. ast_debug(1, "got port of %s\n", pgdbport);
  569. ast_debug(1, "got user of %s\n", pgdbuser);
  570. ast_debug(1, "got dbname of %s\n", pgdbname);
  571. ast_debug(1, "got password of %s\n", pgpassword);
  572. ast_debug(1, "got application name of %s\n", pgappname);
  573. ast_debug(1, "got sql table name of %s\n", table);
  574. ast_debug(1, "got encoding of %s\n", encoding);
  575. ast_debug(1, "got timezone of %s\n", tz);
  576. }
  577. pgsql_reconnect();
  578. if (PQstatus(conn) != CONNECTION_BAD) {
  579. char sqlcmd[768];
  580. char *fname, *ftype, *flen, *fnotnull, *fdef;
  581. int i, rows, version;
  582. ast_debug(1, "Successfully connected to PostgreSQL database.\n");
  583. connected = 1;
  584. connect_time = time(NULL);
  585. records = 0;
  586. if (PQsetClientEncoding(conn, encoding)) {
  587. #ifdef HAVE_PGSQL_pg_encoding_to_char
  588. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  589. #else
  590. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  591. #endif
  592. }
  593. version = PQserverVersion(conn);
  594. if (version >= 70300) {
  595. char *schemaname, *tablename;
  596. if (strchr(table, '.')) {
  597. schemaname = ast_strdupa(table);
  598. tablename = strchr(schemaname, '.');
  599. *tablename++ = '\0';
  600. } else {
  601. schemaname = "";
  602. tablename = table;
  603. }
  604. /* Escape special characters in schemaname */
  605. if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
  606. char *tmp = schemaname, *ptr;
  607. ptr = schemaname = ast_alloca(strlen(tmp) * 2 + 1);
  608. for (; *tmp; tmp++) {
  609. if (strchr("\\'", *tmp)) {
  610. *ptr++ = *tmp;
  611. }
  612. *ptr++ = *tmp;
  613. }
  614. *ptr = '\0';
  615. }
  616. /* Escape special characters in tablename */
  617. if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
  618. char *tmp = tablename, *ptr;
  619. ptr = tablename = ast_alloca(strlen(tmp) * 2 + 1);
  620. for (; *tmp; tmp++) {
  621. if (strchr("\\'", *tmp)) {
  622. *ptr++ = *tmp;
  623. }
  624. *ptr++ = *tmp;
  625. }
  626. *ptr = '\0';
  627. }
  628. snprintf(sqlcmd, sizeof(sqlcmd), "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",
  629. tablename,
  630. ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
  631. } else {
  632. snprintf(sqlcmd, sizeof(sqlcmd), "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", table);
  633. }
  634. /* Query the columns */
  635. result = PQexec(conn, sqlcmd);
  636. if (PQresultStatus(result) != PGRES_TUPLES_OK) {
  637. pgerror = PQresultErrorMessage(result);
  638. ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
  639. PQclear(result);
  640. unload_module();
  641. ast_mutex_unlock(&pgsql_lock);
  642. return AST_MODULE_LOAD_DECLINE;
  643. }
  644. rows = PQntuples(result);
  645. if (rows == 0) {
  646. ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
  647. PQclear(result);
  648. unload_module();
  649. ast_mutex_unlock(&pgsql_lock);
  650. return AST_MODULE_LOAD_DECLINE;
  651. }
  652. /* Clear out the columns list. */
  653. empty_columns();
  654. for (i = 0; i < rows; i++) {
  655. fname = PQgetvalue(result, i, 0);
  656. ftype = PQgetvalue(result, i, 1);
  657. flen = PQgetvalue(result, i, 2);
  658. fnotnull = PQgetvalue(result, i, 3);
  659. fdef = PQgetvalue(result, i, 4);
  660. if (atoi(flen) == -1) {
  661. /* For varchar columns, the maximum length is encoded in a different field */
  662. flen = PQgetvalue(result, i, 5);
  663. }
  664. cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
  665. if (cur) {
  666. sscanf(flen, "%30d", &cur->len);
  667. cur->name = (char *)cur + sizeof(*cur);
  668. cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
  669. strcpy(cur->name, fname);
  670. strcpy(cur->type, ftype);
  671. if (*fnotnull == 't') {
  672. cur->notnull = 1;
  673. } else {
  674. cur->notnull = 0;
  675. }
  676. if (!ast_strlen_zero(fdef)) {
  677. cur->hasdefault = 1;
  678. } else {
  679. cur->hasdefault = 0;
  680. }
  681. AST_RWLIST_WRLOCK(&psql_columns);
  682. AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
  683. AST_RWLIST_UNLOCK(&psql_columns);
  684. }
  685. }
  686. PQclear(result);
  687. } else {
  688. pgerror = PQerrorMessage(conn);
  689. ast_log(LOG_ERROR, "Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
  690. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  691. connected = 0;
  692. PQfinish(conn);
  693. conn = NULL;
  694. }
  695. ast_config_destroy(cfg);
  696. ast_mutex_unlock(&pgsql_lock);
  697. return 0;
  698. }
  699. static int load_module(void)
  700. {
  701. ast_cli_register_multiple(cdr_pgsql_status_cli, sizeof(cdr_pgsql_status_cli) / sizeof(struct ast_cli_entry));
  702. if (config_module(0)) {
  703. return AST_MODULE_LOAD_DECLINE;
  704. }
  705. return ast_cdr_register(name, ast_module_info->description, pgsql_log)
  706. ? AST_MODULE_LOAD_DECLINE : 0;
  707. }
  708. static int reload(void)
  709. {
  710. return config_module(1);
  711. }
  712. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
  713. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  714. .load = load_module,
  715. .unload = unload_module,
  716. .reload = reload,
  717. .load_pri = AST_MODPRI_CDR_DRIVER,
  718. );