cdr_pgsql.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. * \extref PostgreSQL http://www.postgresql.org/
  28. *
  29. * See also
  30. * \arg \ref Config_cdr
  31. * \extref PostgreSQL http://www.postgresql.org/
  32. * \ingroup cdr_drivers
  33. */
  34. /*** MODULEINFO
  35. <depend>pgsql</depend>
  36. <support_level>extended</support_level>
  37. <defaultenabled>no</defaultenabled>
  38. ***/
  39. #include "asterisk.h"
  40. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  41. #include <libpq-fe.h>
  42. #include "asterisk/config.h"
  43. #include "asterisk/channel.h"
  44. #include "asterisk/cdr.h"
  45. #include "asterisk/module.h"
  46. #define DATE_FORMAT "'%Y-%m-%d %T'"
  47. static const char name[] = "pgsql";
  48. static const char config[] = "cdr_pgsql.conf";
  49. static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL, *encoding = NULL, *tz = NULL;
  50. static int connected = 0;
  51. static int maxsize = 512, maxsize2 = 512;
  52. AST_MUTEX_DEFINE_STATIC(pgsql_lock);
  53. static PGconn *conn = NULL;
  54. struct columns {
  55. char *name;
  56. char *type;
  57. int len;
  58. unsigned int notnull:1;
  59. unsigned int hasdefault:1;
  60. AST_RWLIST_ENTRY(columns) list;
  61. };
  62. static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
  63. #define LENGTHEN_BUF1(size) \
  64. do { \
  65. /* Lengthen buffer, if necessary */ \
  66. if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
  67. if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) { \
  68. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  69. ast_free(sql); \
  70. ast_free(sql2); \
  71. AST_RWLIST_UNLOCK(&psql_columns); \
  72. ast_mutex_unlock(&pgsql_lock); \
  73. return -1; \
  74. } \
  75. } \
  76. } while (0)
  77. #define LENGTHEN_BUF2(size) \
  78. do { \
  79. if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
  80. if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
  81. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  82. ast_free(sql); \
  83. ast_free(sql2); \
  84. AST_RWLIST_UNLOCK(&psql_columns); \
  85. ast_mutex_unlock(&pgsql_lock); \
  86. return -1; \
  87. } \
  88. } \
  89. } while (0)
  90. static int pgsql_log(struct ast_cdr *cdr)
  91. {
  92. struct ast_tm tm;
  93. char *pgerror;
  94. PGresult *result;
  95. ast_mutex_lock(&pgsql_lock);
  96. if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
  97. conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
  98. if (PQstatus(conn) != CONNECTION_BAD) {
  99. connected = 1;
  100. if (PQsetClientEncoding(conn, encoding)) {
  101. #ifdef HAVE_PGSQL_pg_encoding_to_char
  102. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  103. #else
  104. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  105. #endif
  106. }
  107. } else {
  108. pgerror = PQerrorMessage(conn);
  109. ast_log(LOG_ERROR, "Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
  110. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  111. PQfinish(conn);
  112. conn = NULL;
  113. }
  114. }
  115. if (connected) {
  116. struct columns *cur;
  117. struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
  118. char buf[257], escapebuf[513], *value;
  119. int first = 1;
  120. if (!sql || !sql2) {
  121. ast_free(sql);
  122. ast_free(sql2);
  123. return -1;
  124. }
  125. ast_str_set(&sql, 0, "INSERT INTO %s (", table);
  126. ast_str_set(&sql2, 0, " VALUES (");
  127. AST_RWLIST_RDLOCK(&psql_columns);
  128. AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
  129. /* For fields not set, simply skip them */
  130. ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
  131. if (strcmp(cur->name, "calldate") == 0 && !value) {
  132. ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 0);
  133. }
  134. if (!value) {
  135. if (cur->notnull && !cur->hasdefault) {
  136. /* Field is NOT NULL (but no default), must include it anyway */
  137. LENGTHEN_BUF1(strlen(cur->name) + 2);
  138. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  139. LENGTHEN_BUF2(3);
  140. ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
  141. first = 0;
  142. }
  143. continue;
  144. }
  145. LENGTHEN_BUF1(strlen(cur->name) + 2);
  146. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  147. if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
  148. if (strncmp(cur->type, "int", 3) == 0) {
  149. LENGTHEN_BUF2(13);
  150. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
  151. } else if (strncmp(cur->type, "float", 5) == 0) {
  152. LENGTHEN_BUF2(31);
  153. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
  154. } else {
  155. /* char, hopefully */
  156. LENGTHEN_BUF2(31);
  157. ast_localtime(&cdr->start, &tm, tz);
  158. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  159. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  160. }
  161. } else if (strcmp(cur->name, "answer") == 0) {
  162. if (strncmp(cur->type, "int", 3) == 0) {
  163. LENGTHEN_BUF2(13);
  164. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
  165. } else if (strncmp(cur->type, "float", 5) == 0) {
  166. LENGTHEN_BUF2(31);
  167. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
  168. } else {
  169. /* char, hopefully */
  170. LENGTHEN_BUF2(31);
  171. ast_localtime(&cdr->answer, &tm, tz);
  172. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  173. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  174. }
  175. } else if (strcmp(cur->name, "end") == 0) {
  176. if (strncmp(cur->type, "int", 3) == 0) {
  177. LENGTHEN_BUF2(13);
  178. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
  179. } else if (strncmp(cur->type, "float", 5) == 0) {
  180. LENGTHEN_BUF2(31);
  181. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
  182. } else {
  183. /* char, hopefully */
  184. LENGTHEN_BUF2(31);
  185. ast_localtime(&cdr->end, &tm, tz);
  186. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  187. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  188. }
  189. } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
  190. if (cur->type[0] == 'i') {
  191. /* Get integer, no need to escape anything */
  192. ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
  193. LENGTHEN_BUF2(13);
  194. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  195. } else if (strncmp(cur->type, "float", 5) == 0) {
  196. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  197. LENGTHEN_BUF2(31);
  198. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  199. } else {
  200. /* Char field, probably */
  201. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  202. LENGTHEN_BUF2(31);
  203. ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  204. }
  205. } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
  206. if (strncmp(cur->type, "int", 3) == 0) {
  207. /* Integer, no need to escape anything */
  208. ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
  209. LENGTHEN_BUF2(13);
  210. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  211. } else {
  212. /* Although this is a char field, there are no special characters in the values for these fields */
  213. ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
  214. LENGTHEN_BUF2(31);
  215. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
  216. }
  217. } else {
  218. /* Arbitrary field, could be anything */
  219. ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
  220. if (strncmp(cur->type, "int", 3) == 0) {
  221. long long whatever;
  222. if (value && sscanf(value, "%30lld", &whatever) == 1) {
  223. LENGTHEN_BUF2(26);
  224. ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
  225. } else {
  226. LENGTHEN_BUF2(2);
  227. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  228. }
  229. } else if (strncmp(cur->type, "float", 5) == 0) {
  230. long double whatever;
  231. if (value && sscanf(value, "%30Lf", &whatever) == 1) {
  232. LENGTHEN_BUF2(51);
  233. ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
  234. } else {
  235. LENGTHEN_BUF2(2);
  236. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  237. }
  238. /* XXX Might want to handle dates, times, and other misc fields here XXX */
  239. } else {
  240. if (value)
  241. PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
  242. else
  243. escapebuf[0] = '\0';
  244. LENGTHEN_BUF2(strlen(escapebuf) + 3);
  245. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
  246. }
  247. }
  248. first = 0;
  249. }
  250. LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
  251. AST_RWLIST_UNLOCK(&psql_columns);
  252. ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
  253. ast_verb(11, "[%s]\n", ast_str_buffer(sql));
  254. ast_debug(2, "inserting a CDR record.\n");
  255. /* Test to be sure we're still connected... */
  256. /* If we're connected, and connection is working, good. */
  257. /* Otherwise, attempt reconnect. If it fails... sorry... */
  258. if (PQstatus(conn) == CONNECTION_OK) {
  259. connected = 1;
  260. } else {
  261. ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
  262. PQreset(conn);
  263. if (PQstatus(conn) == CONNECTION_OK) {
  264. ast_log(LOG_ERROR, "Connection reestablished.\n");
  265. connected = 1;
  266. } else {
  267. pgerror = PQerrorMessage(conn);
  268. ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
  269. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  270. PQfinish(conn);
  271. conn = NULL;
  272. connected = 0;
  273. ast_mutex_unlock(&pgsql_lock);
  274. ast_free(sql);
  275. ast_free(sql2);
  276. return -1;
  277. }
  278. }
  279. result = PQexec(conn, ast_str_buffer(sql));
  280. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  281. pgerror = PQresultErrorMessage(result);
  282. ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
  283. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  284. ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
  285. PQreset(conn);
  286. if (PQstatus(conn) == CONNECTION_OK) {
  287. ast_log(LOG_ERROR, "Connection reestablished.\n");
  288. connected = 1;
  289. PQclear(result);
  290. result = PQexec(conn, ast_str_buffer(sql));
  291. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  292. pgerror = PQresultErrorMessage(result);
  293. ast_log(LOG_ERROR, "HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
  294. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  295. }
  296. }
  297. ast_mutex_unlock(&pgsql_lock);
  298. PQclear(result);
  299. ast_free(sql);
  300. ast_free(sql2);
  301. return -1;
  302. }
  303. PQclear(result);
  304. ast_free(sql);
  305. ast_free(sql2);
  306. }
  307. ast_mutex_unlock(&pgsql_lock);
  308. return 0;
  309. }
  310. /* This function should be called without holding the pgsql_columns lock */
  311. static void empty_columns(void)
  312. {
  313. struct columns *current;
  314. AST_RWLIST_WRLOCK(&psql_columns);
  315. while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
  316. ast_free(current);
  317. }
  318. AST_RWLIST_UNLOCK(&psql_columns);
  319. }
  320. static int unload_module(void)
  321. {
  322. ast_cdr_unregister(name);
  323. PQfinish(conn);
  324. ast_free(pghostname);
  325. ast_free(pgdbname);
  326. ast_free(pgdbuser);
  327. ast_free(pgpassword);
  328. ast_free(pgdbport);
  329. ast_free(table);
  330. ast_free(encoding);
  331. ast_free(tz);
  332. empty_columns();
  333. return 0;
  334. }
  335. static int config_module(int reload)
  336. {
  337. struct ast_variable *var;
  338. char *pgerror;
  339. struct columns *cur;
  340. PGresult *result;
  341. const char *tmp;
  342. struct ast_config *cfg;
  343. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  344. if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
  345. ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
  346. return -1;
  347. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  348. return 0;
  349. }
  350. ast_mutex_lock(&pgsql_lock);
  351. if (!(var = ast_variable_browse(cfg, "global"))) {
  352. ast_config_destroy(cfg);
  353. ast_mutex_unlock(&pgsql_lock);
  354. ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
  355. reload ? "reload" : "load");
  356. return -1;
  357. }
  358. if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
  359. ast_log(LOG_WARNING, "PostgreSQL server hostname not specified. Assuming unix socket connection\n");
  360. tmp = ""; /* connect via UNIX-socket by default */
  361. }
  362. ast_free(pghostname);
  363. if (!(pghostname = ast_strdup(tmp))) {
  364. ast_config_destroy(cfg);
  365. ast_mutex_unlock(&pgsql_lock);
  366. return -1;
  367. }
  368. if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
  369. ast_log(LOG_WARNING, "PostgreSQL database not specified. Assuming asterisk\n");
  370. tmp = "asteriskcdrdb";
  371. }
  372. ast_free(pgdbname);
  373. if (!(pgdbname = ast_strdup(tmp))) {
  374. ast_config_destroy(cfg);
  375. ast_mutex_unlock(&pgsql_lock);
  376. return -1;
  377. }
  378. if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
  379. ast_log(LOG_WARNING, "PostgreSQL database user not specified. Assuming asterisk\n");
  380. tmp = "asterisk";
  381. }
  382. ast_free(pgdbuser);
  383. if (!(pgdbuser = ast_strdup(tmp))) {
  384. ast_config_destroy(cfg);
  385. ast_mutex_unlock(&pgsql_lock);
  386. return -1;
  387. }
  388. if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
  389. ast_log(LOG_WARNING, "PostgreSQL database password not specified. Assuming blank\n");
  390. tmp = "";
  391. }
  392. ast_free(pgpassword);
  393. if (!(pgpassword = ast_strdup(tmp))) {
  394. ast_config_destroy(cfg);
  395. ast_mutex_unlock(&pgsql_lock);
  396. return -1;
  397. }
  398. if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
  399. ast_log(LOG_WARNING, "PostgreSQL database port not specified. Using default 5432.\n");
  400. tmp = "5432";
  401. }
  402. ast_free(pgdbport);
  403. if (!(pgdbport = ast_strdup(tmp))) {
  404. ast_config_destroy(cfg);
  405. ast_mutex_unlock(&pgsql_lock);
  406. return -1;
  407. }
  408. if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
  409. ast_log(LOG_WARNING, "CDR table not specified. Assuming cdr\n");
  410. tmp = "cdr";
  411. }
  412. ast_free(table);
  413. if (!(table = ast_strdup(tmp))) {
  414. ast_config_destroy(cfg);
  415. ast_mutex_unlock(&pgsql_lock);
  416. return -1;
  417. }
  418. if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
  419. ast_log(LOG_WARNING, "Encoding not specified. Assuming LATIN9\n");
  420. tmp = "LATIN9";
  421. }
  422. ast_free(encoding);
  423. if (!(encoding = ast_strdup(tmp))) {
  424. ast_config_destroy(cfg);
  425. ast_mutex_unlock(&pgsql_lock);
  426. return -1;
  427. }
  428. if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
  429. tmp = "";
  430. }
  431. ast_free(tz);
  432. tz = NULL;
  433. if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
  434. ast_config_destroy(cfg);
  435. ast_mutex_unlock(&pgsql_lock);
  436. return -1;
  437. }
  438. if (option_debug) {
  439. if (ast_strlen_zero(pghostname)) {
  440. ast_debug(1, "using default unix socket\n");
  441. } else {
  442. ast_debug(1, "got hostname of %s\n", pghostname);
  443. }
  444. ast_debug(1, "got port of %s\n", pgdbport);
  445. ast_debug(1, "got user of %s\n", pgdbuser);
  446. ast_debug(1, "got dbname of %s\n", pgdbname);
  447. ast_debug(1, "got password of %s\n", pgpassword);
  448. ast_debug(1, "got sql table name of %s\n", table);
  449. ast_debug(1, "got encoding of %s\n", encoding);
  450. ast_debug(1, "got timezone of %s\n", tz);
  451. }
  452. conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
  453. if (PQstatus(conn) != CONNECTION_BAD) {
  454. char sqlcmd[768];
  455. char *fname, *ftype, *flen, *fnotnull, *fdef;
  456. int i, rows, version;
  457. ast_debug(1, "Successfully connected to PostgreSQL database.\n");
  458. connected = 1;
  459. if (PQsetClientEncoding(conn, encoding)) {
  460. #ifdef HAVE_PGSQL_pg_encoding_to_char
  461. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  462. #else
  463. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  464. #endif
  465. }
  466. version = PQserverVersion(conn);
  467. if (version >= 70300) {
  468. char *schemaname, *tablename;
  469. if (strchr(table, '.')) {
  470. schemaname = ast_strdupa(table);
  471. tablename = strchr(schemaname, '.');
  472. *tablename++ = '\0';
  473. } else {
  474. schemaname = "";
  475. tablename = table;
  476. }
  477. /* Escape special characters in schemaname */
  478. if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
  479. char *tmp = schemaname, *ptr;
  480. ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
  481. for (; *tmp; tmp++) {
  482. if (strchr("\\'", *tmp)) {
  483. *ptr++ = *tmp;
  484. }
  485. *ptr++ = *tmp;
  486. }
  487. *ptr = '\0';
  488. }
  489. /* Escape special characters in tablename */
  490. if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
  491. char *tmp = tablename, *ptr;
  492. ptr = tablename = alloca(strlen(tmp) * 2 + 1);
  493. for (; *tmp; tmp++) {
  494. if (strchr("\\'", *tmp)) {
  495. *ptr++ = *tmp;
  496. }
  497. *ptr++ = *tmp;
  498. }
  499. *ptr = '\0';
  500. }
  501. 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",
  502. tablename,
  503. ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
  504. } else {
  505. 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);
  506. }
  507. /* Query the columns */
  508. result = PQexec(conn, sqlcmd);
  509. if (PQresultStatus(result) != PGRES_TUPLES_OK) {
  510. pgerror = PQresultErrorMessage(result);
  511. ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
  512. PQclear(result);
  513. unload_module();
  514. ast_mutex_unlock(&pgsql_lock);
  515. return AST_MODULE_LOAD_DECLINE;
  516. }
  517. rows = PQntuples(result);
  518. if (rows == 0) {
  519. ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
  520. PQclear(result);
  521. unload_module();
  522. ast_mutex_unlock(&pgsql_lock);
  523. return AST_MODULE_LOAD_DECLINE;
  524. }
  525. /* Clear out the columns list. */
  526. empty_columns();
  527. for (i = 0; i < rows; i++) {
  528. fname = PQgetvalue(result, i, 0);
  529. ftype = PQgetvalue(result, i, 1);
  530. flen = PQgetvalue(result, i, 2);
  531. fnotnull = PQgetvalue(result, i, 3);
  532. fdef = PQgetvalue(result, i, 4);
  533. if (atoi(flen) == -1) {
  534. /* For varchar columns, the maximum length is encoded in a different field */
  535. flen = PQgetvalue(result, i, 5);
  536. }
  537. ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
  538. cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
  539. if (cur) {
  540. sscanf(flen, "%30d", &cur->len);
  541. cur->name = (char *)cur + sizeof(*cur);
  542. cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
  543. strcpy(cur->name, fname);
  544. strcpy(cur->type, ftype);
  545. if (*fnotnull == 't') {
  546. cur->notnull = 1;
  547. } else {
  548. cur->notnull = 0;
  549. }
  550. if (!ast_strlen_zero(fdef)) {
  551. cur->hasdefault = 1;
  552. } else {
  553. cur->hasdefault = 0;
  554. }
  555. AST_RWLIST_WRLOCK(&psql_columns);
  556. AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
  557. AST_RWLIST_UNLOCK(&psql_columns);
  558. }
  559. }
  560. PQclear(result);
  561. } else {
  562. pgerror = PQerrorMessage(conn);
  563. ast_log(LOG_ERROR, "Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
  564. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  565. connected = 0;
  566. }
  567. ast_config_destroy(cfg);
  568. ast_mutex_unlock(&pgsql_lock);
  569. return 0;
  570. }
  571. static int load_module(void)
  572. {
  573. if (config_module(0)) {
  574. return AST_MODULE_LOAD_DECLINE;
  575. }
  576. return ast_cdr_register(name, ast_module_info->description, pgsql_log)
  577. ? AST_MODULE_LOAD_DECLINE : 0;
  578. }
  579. static int reload(void)
  580. {
  581. return config_module(1);
  582. }
  583. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
  584. .load = load_module,
  585. .unload = unload_module,
  586. .reload = reload,
  587. .load_pri = AST_MODPRI_CDR_DRIVER,
  588. );