cdr_pgsql.c 21 KB

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