res_odbc.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2012, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * res_odbc.c <ODBC resource manager>
  9. * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
  10. *
  11. * See http://www.asterisk.org for more information about
  12. * the Asterisk project. Please do not directly contact
  13. * any of the maintainers of this project for assistance;
  14. * the project provides a web site, mailing lists and IRC
  15. * channels for your use.
  16. *
  17. * This program is free software, distributed under the terms of
  18. * the GNU General Public License Version 2. See the LICENSE file
  19. * at the top of the source tree.
  20. */
  21. /*! \file
  22. *
  23. * \brief ODBC resource manager
  24. *
  25. * \author Mark Spencer <markster@digium.com>
  26. * \author Anthony Minessale II <anthmct@yahoo.com>
  27. * \author Tilghman Lesher <tilghman@digium.com>
  28. *
  29. * \arg See also: \ref cdr_odbc
  30. */
  31. /*! \li \ref res_odbc.c uses the configuration file \ref res_odbc.conf
  32. * \addtogroup configuration_file Configuration Files
  33. */
  34. /*!
  35. * \page res_odbc.conf res_odbc.conf
  36. * \verbinclude res_odbc.conf.sample
  37. */
  38. /*** MODULEINFO
  39. <depend>generic_odbc</depend>
  40. <depend>res_odbc_transaction</depend>
  41. <support_level>core</support_level>
  42. ***/
  43. #include "asterisk.h"
  44. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  45. #include "asterisk/file.h"
  46. #include "asterisk/channel.h"
  47. #include "asterisk/config.h"
  48. #include "asterisk/pbx.h"
  49. #include "asterisk/module.h"
  50. #include "asterisk/cli.h"
  51. #include "asterisk/lock.h"
  52. #include "asterisk/res_odbc.h"
  53. #include "asterisk/time.h"
  54. #include "asterisk/astobj2.h"
  55. #include "asterisk/app.h"
  56. #include "asterisk/strings.h"
  57. #include "asterisk/threadstorage.h"
  58. #include "asterisk/data.h"
  59. struct odbc_class
  60. {
  61. AST_LIST_ENTRY(odbc_class) list;
  62. char name[80];
  63. char dsn[80];
  64. char *username;
  65. char *password;
  66. char *sanitysql;
  67. SQLHENV env;
  68. unsigned int delme:1; /*!< Purge the class */
  69. unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
  70. unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
  71. unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
  72. unsigned int conntimeout; /*!< Maximum time the connection process should take */
  73. unsigned int maxconnections; /*!< Maximum number of allowed connections */
  74. /*! When a connection fails, cache that failure for how long? */
  75. struct timeval negative_connection_cache;
  76. /*! When a connection fails, when did that last occur? */
  77. struct timeval last_negative_connect;
  78. /*! A pool of available connections */
  79. AST_LIST_HEAD_NOLOCK(, odbc_obj) connections;
  80. /*! Lock to protect the connections */
  81. ast_mutex_t lock;
  82. /*! Condition to notify any pending connection requesters */
  83. ast_cond_t cond;
  84. /*! The total number of current connections */
  85. size_t connection_cnt;
  86. };
  87. static struct ao2_container *class_container;
  88. static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
  89. static odbc_status odbc_obj_connect(struct odbc_obj *obj);
  90. static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
  91. static void odbc_register_class(struct odbc_class *class, int connect);
  92. AST_THREADSTORAGE(errors_buf);
  93. struct odbc_txn_frame {
  94. AST_LIST_ENTRY(odbc_txn_frame) list;
  95. struct ast_channel *owner;
  96. struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
  97. /*!\brief Is this record the current active transaction within the channel?
  98. * Note that the active flag is really only necessary for statements which
  99. * are triggered from the dialplan, as there isn't a direct correlation
  100. * between multiple statements. Applications wishing to use transactions
  101. * may simply perform each statement on the same odbc_obj, which keeps the
  102. * transaction persistent.
  103. */
  104. unsigned int active:1;
  105. unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
  106. unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
  107. char name[0]; /*!< Name of this transaction ID */
  108. };
  109. #define DATA_EXPORT_ODBC_CLASS(MEMBER) \
  110. MEMBER(odbc_class, name, AST_DATA_STRING) \
  111. MEMBER(odbc_class, dsn, AST_DATA_STRING) \
  112. MEMBER(odbc_class, username, AST_DATA_STRING) \
  113. MEMBER(odbc_class, password, AST_DATA_PASSWORD) \
  114. MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
  115. AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
  116. const char *ast_odbc_isolation2text(int iso)
  117. {
  118. if (iso == SQL_TXN_READ_COMMITTED) {
  119. return "read_committed";
  120. } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
  121. return "read_uncommitted";
  122. } else if (iso == SQL_TXN_SERIALIZABLE) {
  123. return "serializable";
  124. } else if (iso == SQL_TXN_REPEATABLE_READ) {
  125. return "repeatable_read";
  126. } else {
  127. return "unknown";
  128. }
  129. }
  130. int ast_odbc_text2isolation(const char *txt)
  131. {
  132. if (strncasecmp(txt, "read_", 5) == 0) {
  133. if (strncasecmp(txt + 5, "c", 1) == 0) {
  134. return SQL_TXN_READ_COMMITTED;
  135. } else if (strncasecmp(txt + 5, "u", 1) == 0) {
  136. return SQL_TXN_READ_UNCOMMITTED;
  137. } else {
  138. return 0;
  139. }
  140. } else if (strncasecmp(txt, "ser", 3) == 0) {
  141. return SQL_TXN_SERIALIZABLE;
  142. } else if (strncasecmp(txt, "rep", 3) == 0) {
  143. return SQL_TXN_REPEATABLE_READ;
  144. } else {
  145. return 0;
  146. }
  147. }
  148. static void odbc_class_destructor(void *data)
  149. {
  150. struct odbc_class *class = data;
  151. struct odbc_obj *obj;
  152. /* Due to refcounts, we can safely assume that any objects with a reference
  153. * to us will prevent our destruction, so we don't need to worry about them.
  154. */
  155. if (class->username) {
  156. ast_free(class->username);
  157. }
  158. if (class->password) {
  159. ast_free(class->password);
  160. }
  161. if (class->sanitysql) {
  162. ast_free(class->sanitysql);
  163. }
  164. while ((obj = AST_LIST_REMOVE_HEAD(&class->connections, list))) {
  165. ao2_ref(obj, -1);
  166. }
  167. SQLFreeHandle(SQL_HANDLE_ENV, class->env);
  168. ast_mutex_destroy(&class->lock);
  169. ast_cond_destroy(&class->cond);
  170. }
  171. static void odbc_obj_destructor(void *data)
  172. {
  173. struct odbc_obj *obj = data;
  174. odbc_obj_disconnect(obj);
  175. }
  176. static void destroy_table_cache(struct odbc_cache_tables *table)
  177. {
  178. struct odbc_cache_columns *col;
  179. ast_debug(1, "Destroying table cache for %s\n", table->table);
  180. AST_RWLIST_WRLOCK(&table->columns);
  181. while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
  182. ast_free(col);
  183. }
  184. AST_RWLIST_UNLOCK(&table->columns);
  185. AST_RWLIST_HEAD_DESTROY(&table->columns);
  186. ast_free(table);
  187. }
  188. /*!
  189. * \brief Find or create an entry describing the table specified.
  190. * \param database Name of an ODBC class on which to query the table
  191. * \param tablename Tablename to describe
  192. * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
  193. * When a structure is returned, the contained columns list will be
  194. * rdlock'ed, to ensure that it will be retained in memory.
  195. *
  196. * XXX This creates a connection and disconnects it. In some situations, the caller of
  197. * this function has its own connection and could donate it to this function instead of
  198. * needing to create another one.
  199. *
  200. * XXX The automatic readlock of the columns is awkward. It's done because it's possible for
  201. * multiple threads to have references to the table, and the table is not refcounted. Possible
  202. * changes here would be
  203. * * Eliminate the table cache entirely. The use of ast_odbc_find_table() is generally
  204. * questionable. The only real good use right now is from ast_realtime_require_field() in
  205. * order to make sure the DB has the expected columns in it. Since that is only used sparingly,
  206. * the need to cache tables is questionable. Instead, the table structure can be fetched from
  207. * the DB directly each time, resulting in a single owner of the data.
  208. * * Make odbc_cache_tables a refcounted object.
  209. *
  210. * \since 1.6.1
  211. */
  212. struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
  213. {
  214. struct odbc_cache_tables *tableptr;
  215. struct odbc_cache_columns *entry;
  216. char columnname[80];
  217. SQLLEN sqlptr;
  218. SQLHSTMT stmt = NULL;
  219. int res = 0, error = 0;
  220. struct odbc_obj *obj;
  221. AST_RWLIST_RDLOCK(&odbc_tables);
  222. AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
  223. if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
  224. break;
  225. }
  226. }
  227. if (tableptr) {
  228. AST_RWLIST_RDLOCK(&tableptr->columns);
  229. AST_RWLIST_UNLOCK(&odbc_tables);
  230. return tableptr;
  231. }
  232. if (!(obj = ast_odbc_request_obj(database, 0))) {
  233. ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
  234. AST_RWLIST_UNLOCK(&odbc_tables);
  235. return NULL;
  236. }
  237. /* Table structure not already cached; build it now. */
  238. do {
  239. res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
  240. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  241. ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
  242. break;
  243. }
  244. res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
  245. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  246. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  247. ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
  248. break;
  249. }
  250. if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
  251. ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
  252. break;
  253. }
  254. tableptr->connection = (char *)tableptr + sizeof(*tableptr);
  255. tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
  256. strcpy(tableptr->connection, database); /* SAFE */
  257. strcpy(tableptr->table, tablename); /* SAFE */
  258. AST_RWLIST_HEAD_INIT(&(tableptr->columns));
  259. while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
  260. SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
  261. if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
  262. ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
  263. error = 1;
  264. break;
  265. }
  266. entry->name = (char *)entry + sizeof(*entry);
  267. strcpy(entry->name, columnname);
  268. SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
  269. SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
  270. SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
  271. SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
  272. SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
  273. SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
  274. /* Specification states that the octenlen should be the maximum number of bytes
  275. * returned in a char or binary column, but it seems that some drivers just set
  276. * it to NULL. (Bad Postgres! No biscuit!) */
  277. if (entry->octetlen == 0) {
  278. entry->octetlen = entry->size;
  279. }
  280. ast_debug(3, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
  281. /* Insert column info into column list */
  282. AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
  283. }
  284. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  285. AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
  286. AST_RWLIST_RDLOCK(&(tableptr->columns));
  287. break;
  288. } while (1);
  289. AST_RWLIST_UNLOCK(&odbc_tables);
  290. if (error) {
  291. destroy_table_cache(tableptr);
  292. tableptr = NULL;
  293. }
  294. ast_odbc_release_obj(obj);
  295. return tableptr;
  296. }
  297. struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
  298. {
  299. struct odbc_cache_columns *col;
  300. AST_RWLIST_TRAVERSE(&table->columns, col, list) {
  301. if (strcasecmp(col->name, colname) == 0) {
  302. return col;
  303. }
  304. }
  305. return NULL;
  306. }
  307. int ast_odbc_clear_cache(const char *database, const char *tablename)
  308. {
  309. struct odbc_cache_tables *tableptr;
  310. AST_RWLIST_WRLOCK(&odbc_tables);
  311. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
  312. if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
  313. AST_LIST_REMOVE_CURRENT(list);
  314. destroy_table_cache(tableptr);
  315. break;
  316. }
  317. }
  318. AST_RWLIST_TRAVERSE_SAFE_END
  319. AST_RWLIST_UNLOCK(&odbc_tables);
  320. return tableptr ? 0 : -1;
  321. }
  322. SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
  323. {
  324. SQLHSTMT stmt;
  325. stmt = exec_cb(obj, data);
  326. return stmt;
  327. }
  328. SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
  329. {
  330. int res = 0;
  331. SQLHSTMT stmt;
  332. /* This prepare callback may do more than just prepare -- it may also
  333. * bind parameters, bind results, etc. The real key, here, is that
  334. * when we disconnect, all handles become invalid for most databases.
  335. * We must therefore redo everything when we establish a new
  336. * connection. */
  337. stmt = prepare_cb(obj, data);
  338. if (!stmt) {
  339. return NULL;
  340. }
  341. res = SQLExecute(stmt);
  342. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  343. if (res == SQL_ERROR) {
  344. ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
  345. }
  346. ast_log(LOG_WARNING, "SQL Execute error %d!\n", res);
  347. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  348. stmt = NULL;
  349. }
  350. return stmt;
  351. }
  352. int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
  353. {
  354. int res = 0;
  355. res = SQLExecute(stmt);
  356. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  357. if (res == SQL_ERROR) {
  358. ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
  359. }
  360. }
  361. return res;
  362. }
  363. SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
  364. {
  365. SQLRETURN res;
  366. if (pmaxlen == 0) {
  367. if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
  368. ast_str_make_space(buf, *StrLen_or_Ind + 1);
  369. }
  370. } else if (pmaxlen > 0) {
  371. ast_str_make_space(buf, pmaxlen);
  372. }
  373. res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
  374. ast_str_update(*buf);
  375. return res;
  376. }
  377. struct ast_str *ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
  378. {
  379. struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
  380. SQLINTEGER nativeerror = 0;
  381. SQLSMALLINT diagbytes = 0;
  382. SQLSMALLINT i;
  383. unsigned char state[10];
  384. unsigned char diagnostic[256];
  385. ast_str_reset(errors);
  386. i = 0;
  387. while (SQLGetDiagRec(handle_type, handle, ++i, state, &nativeerror,
  388. diagnostic, sizeof(diagnostic), &diagbytes) == SQL_SUCCESS) {
  389. ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
  390. ast_log(LOG_WARNING, "%s returned an error: %s: %s\n", operation, state, diagnostic);
  391. /* XXX Why is this here? */
  392. if (i > 10) {
  393. ast_log(LOG_WARNING, "There are more than 10 diagnostic records! Ignore the rest.\n");
  394. break;
  395. }
  396. }
  397. return errors;
  398. }
  399. unsigned int ast_odbc_class_get_isolation(struct odbc_class *class)
  400. {
  401. return class->isolation;
  402. }
  403. unsigned int ast_odbc_class_get_forcecommit(struct odbc_class *class)
  404. {
  405. return class->forcecommit;
  406. }
  407. const char *ast_odbc_class_get_name(struct odbc_class *class)
  408. {
  409. return class->name;
  410. }
  411. static int load_odbc_config(void)
  412. {
  413. static char *cfg = "res_odbc.conf";
  414. struct ast_config *config;
  415. struct ast_variable *v;
  416. char *cat;
  417. const char *dsn, *username, *password, *sanitysql;
  418. int enabled, bse, conntimeout, forcecommit, isolation, maxconnections;
  419. struct timeval ncache = { 0, 0 };
  420. int preconnect = 0, res = 0;
  421. struct ast_flags config_flags = { 0 };
  422. struct odbc_class *new;
  423. config = ast_config_load(cfg, config_flags);
  424. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  425. ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
  426. return -1;
  427. }
  428. for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
  429. if (!strcasecmp(cat, "ENV")) {
  430. for (v = ast_variable_browse(config, cat); v; v = v->next) {
  431. setenv(v->name, v->value, 1);
  432. ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
  433. }
  434. } else {
  435. /* Reset all to defaults for each class of odbc connections */
  436. dsn = username = password = sanitysql = NULL;
  437. enabled = 1;
  438. preconnect = 0;
  439. bse = 1;
  440. conntimeout = 10;
  441. forcecommit = 0;
  442. isolation = SQL_TXN_READ_COMMITTED;
  443. maxconnections = 1;
  444. for (v = ast_variable_browse(config, cat); v; v = v->next) {
  445. if (!strcasecmp(v->name, "pooling") ||
  446. !strncasecmp(v->name, "share", 5) ||
  447. !strcasecmp(v->name, "limit") ||
  448. !strcasecmp(v->name, "idlecheck")) {
  449. ast_log(LOG_WARNING, "The 'pooling', 'shared_connections', 'limit', and 'idlecheck' options were replaced by 'max_connections'. See res_odbc.conf.sample.\n");
  450. } else if (!strcasecmp(v->name, "enabled")) {
  451. enabled = ast_true(v->value);
  452. } else if (!strcasecmp(v->name, "pre-connect")) {
  453. preconnect = ast_true(v->value);
  454. } else if (!strcasecmp(v->name, "dsn")) {
  455. dsn = v->value;
  456. } else if (!strcasecmp(v->name, "username")) {
  457. username = v->value;
  458. } else if (!strcasecmp(v->name, "password")) {
  459. password = v->value;
  460. } else if (!strcasecmp(v->name, "sanitysql")) {
  461. sanitysql = v->value;
  462. } else if (!strcasecmp(v->name, "backslash_is_escape")) {
  463. bse = ast_true(v->value);
  464. } else if (!strcasecmp(v->name, "connect_timeout")) {
  465. if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
  466. ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
  467. conntimeout = 10;
  468. }
  469. } else if (!strcasecmp(v->name, "negative_connection_cache")) {
  470. double dncache;
  471. if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
  472. ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
  473. /* 5 minutes sounds like a reasonable default */
  474. ncache.tv_sec = 300;
  475. ncache.tv_usec = 0;
  476. } else {
  477. ncache.tv_sec = (int)dncache;
  478. ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
  479. }
  480. } else if (!strcasecmp(v->name, "forcecommit")) {
  481. forcecommit = ast_true(v->value);
  482. } else if (!strcasecmp(v->name, "isolation")) {
  483. if ((isolation = ast_odbc_text2isolation(v->value)) == 0) {
  484. ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
  485. isolation = SQL_TXN_READ_COMMITTED;
  486. }
  487. } else if (!strcasecmp(v->name, "max_connections")) {
  488. if (sscanf(v->value, "%30d", &maxconnections) != 1 || maxconnections < 1) {
  489. ast_log(LOG_WARNING, "max_connections must be a positive integer\n");
  490. maxconnections = 1;
  491. }
  492. }
  493. }
  494. if (enabled && !ast_strlen_zero(dsn)) {
  495. new = ao2_alloc(sizeof(*new), odbc_class_destructor);
  496. if (!new) {
  497. res = -1;
  498. break;
  499. }
  500. SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
  501. res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
  502. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  503. ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
  504. ao2_ref(new, -1);
  505. return res;
  506. }
  507. new->backslash_is_escape = bse ? 1 : 0;
  508. new->forcecommit = forcecommit ? 1 : 0;
  509. new->isolation = isolation;
  510. new->conntimeout = conntimeout;
  511. new->negative_connection_cache = ncache;
  512. new->maxconnections = maxconnections;
  513. if (cat)
  514. ast_copy_string(new->name, cat, sizeof(new->name));
  515. if (dsn)
  516. ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
  517. if (username && !(new->username = ast_strdup(username))) {
  518. ao2_ref(new, -1);
  519. break;
  520. }
  521. if (password && !(new->password = ast_strdup(password))) {
  522. ao2_ref(new, -1);
  523. break;
  524. }
  525. if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
  526. ao2_ref(new, -1);
  527. break;
  528. }
  529. ast_mutex_init(&new->lock);
  530. ast_cond_init(&new->cond, NULL);
  531. odbc_register_class(new, preconnect);
  532. ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
  533. ao2_ref(new, -1);
  534. new = NULL;
  535. }
  536. }
  537. }
  538. ast_config_destroy(config);
  539. return res;
  540. }
  541. static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  542. {
  543. struct ao2_iterator aoi;
  544. struct odbc_class *class;
  545. int length = 0;
  546. int which = 0;
  547. char *ret = NULL;
  548. switch (cmd) {
  549. case CLI_INIT:
  550. e->command = "odbc show";
  551. e->usage =
  552. "Usage: odbc show [class]\n"
  553. " List settings of a particular ODBC class or,\n"
  554. " if not specified, all classes.\n";
  555. return NULL;
  556. case CLI_GENERATE:
  557. if (a->pos != 2)
  558. return NULL;
  559. length = strlen(a->word);
  560. aoi = ao2_iterator_init(class_container, 0);
  561. while ((class = ao2_iterator_next(&aoi))) {
  562. if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
  563. ret = ast_strdup(class->name);
  564. }
  565. ao2_ref(class, -1);
  566. if (ret) {
  567. break;
  568. }
  569. }
  570. ao2_iterator_destroy(&aoi);
  571. if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
  572. ret = ast_strdup("all");
  573. }
  574. return ret;
  575. }
  576. ast_cli(a->fd, "\nODBC DSN Settings\n");
  577. ast_cli(a->fd, "-----------------\n\n");
  578. aoi = ao2_iterator_init(class_container, 0);
  579. while ((class = ao2_iterator_next(&aoi))) {
  580. if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
  581. char timestr[80];
  582. struct ast_tm tm;
  583. ast_localtime(&class->last_negative_connect, &tm, NULL);
  584. ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
  585. ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
  586. ast_cli(a->fd, " Last connection attempt: %s\n", timestr);
  587. ast_cli(a->fd, " Number of active connections: %zd (out of %d)\n", class->connection_cnt, class->maxconnections);
  588. ast_cli(a->fd, "\n");
  589. }
  590. ao2_ref(class, -1);
  591. }
  592. ao2_iterator_destroy(&aoi);
  593. return CLI_SUCCESS;
  594. }
  595. static struct ast_cli_entry cli_odbc[] = {
  596. AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
  597. };
  598. static void odbc_register_class(struct odbc_class *class, int preconnect)
  599. {
  600. struct odbc_obj *obj;
  601. ao2_link(class_container, class);
  602. /* I still have a reference in the caller, so a deref is NOT missing here. */
  603. if (!preconnect) {
  604. return;
  605. }
  606. /* Request and release builds a connection */
  607. obj = ast_odbc_request_obj(class->name, 0);
  608. if (obj) {
  609. ast_odbc_release_obj(obj);
  610. }
  611. return;
  612. }
  613. void ast_odbc_release_obj(struct odbc_obj *obj)
  614. {
  615. struct odbc_class *class = obj->parent;
  616. ast_debug(2, "Releasing ODBC handle %p into pool\n", obj);
  617. /* The odbc_obj only holds a reference to the class when it is
  618. * actively being used. This guarantees no circular reference
  619. * between odbc_class and odbc_obj. Since it is being released
  620. * we also release our class reference. If a reload occurred before
  621. * the class will go away automatically once all odbc_obj are
  622. * released back.
  623. */
  624. obj->parent = NULL;
  625. ast_mutex_lock(&class->lock);
  626. AST_LIST_INSERT_HEAD(&class->connections, obj, list);
  627. ast_cond_signal(&class->cond);
  628. ast_mutex_unlock(&class->lock);
  629. ao2_ref(class, -1);
  630. }
  631. int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
  632. {
  633. return obj->parent->backslash_is_escape;
  634. }
  635. static int aoro2_class_cb(void *obj, void *arg, int flags)
  636. {
  637. struct odbc_class *class = obj;
  638. char *name = arg;
  639. if (!strcmp(class->name, name) && !class->delme) {
  640. return CMP_MATCH | CMP_STOP;
  641. }
  642. return 0;
  643. }
  644. unsigned int ast_odbc_get_max_connections(const char *name)
  645. {
  646. struct odbc_class *class;
  647. unsigned int max_connections;
  648. class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name);
  649. if (!class) {
  650. return 0;
  651. }
  652. max_connections = class->maxconnections;
  653. ao2_ref(class, -1);
  654. return max_connections;
  655. }
  656. /*
  657. * \brief Determine if the connection has died.
  658. *
  659. * \param connection The connection to check
  660. * \param class The ODBC class
  661. * \retval 1 Yep, it's dead
  662. * \retval 0 It's alive and well
  663. */
  664. static int connection_dead(struct odbc_obj *connection, struct odbc_class *class)
  665. {
  666. char *test_sql = "select 1";
  667. SQLINTEGER dead;
  668. SQLRETURN res;
  669. SQLHSTMT stmt;
  670. res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
  671. if (SQL_SUCCEEDED(res)) {
  672. return dead == SQL_CD_TRUE ? 1 : 0;
  673. }
  674. /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a
  675. * probing query instead
  676. */
  677. res = SQLAllocHandle(SQL_HANDLE_STMT, connection->con, &stmt);
  678. if (!SQL_SUCCEEDED(res)) {
  679. return 1;
  680. }
  681. if (!ast_strlen_zero(class->sanitysql)) {
  682. test_sql = class->sanitysql;
  683. }
  684. res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
  685. if (!SQL_SUCCEEDED(res)) {
  686. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  687. return 1;
  688. }
  689. res = SQLExecute(stmt);
  690. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  691. return SQL_SUCCEEDED(res) ? 0 : 1;
  692. }
  693. struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
  694. {
  695. struct odbc_obj *obj = NULL;
  696. struct odbc_class *class;
  697. if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
  698. ast_debug(1, "Class '%s' not found!\n", name);
  699. return NULL;
  700. }
  701. ast_mutex_lock(&class->lock);
  702. while (!obj) {
  703. obj = AST_LIST_REMOVE_HEAD(&class->connections, list);
  704. if (!obj) {
  705. if (class->connection_cnt < class->maxconnections) {
  706. /* If no connection is immediately available establish a new
  707. * one if allowed. If we try and fail we give up completely as
  708. * we could go into an infinite loop otherwise.
  709. */
  710. obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
  711. if (!obj) {
  712. break;
  713. }
  714. obj->parent = ao2_bump(class);
  715. if (odbc_obj_connect(obj) == ODBC_FAIL) {
  716. ao2_ref(obj->parent, -1);
  717. ao2_ref(obj, -1);
  718. obj = NULL;
  719. break;
  720. }
  721. class->connection_cnt++;
  722. ast_debug(2, "Created ODBC handle %p on class '%s', new count is %zd\n", obj,
  723. name, class->connection_cnt);
  724. } else {
  725. /* Otherwise if we're not allowed to create a new one we
  726. * wait for another thread to give up the connection they
  727. * own.
  728. */
  729. ast_cond_wait(&class->cond, &class->lock);
  730. }
  731. } else if (connection_dead(obj, class)) {
  732. /* If the connection is dead try to grab another functional one from the
  733. * pool instead of trying to resurrect this one.
  734. */
  735. ao2_ref(obj, -1);
  736. obj = NULL;
  737. class->connection_cnt--;
  738. ast_debug(2, "ODBC handle %p dead - removing from class '%s', new count is %zd\n",
  739. obj, name, class->connection_cnt);
  740. } else {
  741. /* We successfully grabbed a connection from the pool and all is well!
  742. */
  743. obj->parent = ao2_bump(class);
  744. ast_debug(2, "Reusing ODBC handle %p from class '%s'\n", obj, name);
  745. }
  746. }
  747. ast_mutex_unlock(&class->lock);
  748. ao2_ref(class, -1);
  749. return obj;
  750. }
  751. struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
  752. {
  753. struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
  754. /* XXX New flow means that the "check" parameter doesn't do anything. We're requesting
  755. * a connection from ODBC. We'll either get a new one, which obviously is already connected, or
  756. * we'll get one from the ODBC connection pool. In that case, it will ensure to only give us a
  757. * live connection
  758. */
  759. return _ast_odbc_request_obj2(name, flags, file, function, lineno);
  760. }
  761. static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
  762. {
  763. int res;
  764. SQLINTEGER err;
  765. short int mlen;
  766. unsigned char msg[200], state[10];
  767. SQLHDBC con;
  768. /* Nothing to disconnect */
  769. if (!obj->con) {
  770. return ODBC_SUCCESS;
  771. }
  772. con = obj->con;
  773. obj->con = NULL;
  774. res = SQLDisconnect(con);
  775. if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) == SQL_SUCCESS) {
  776. ast_debug(3, "Database handle %p (connection %p) deallocated\n", obj, con);
  777. } else {
  778. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  779. ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
  780. }
  781. return ODBC_SUCCESS;
  782. }
  783. static odbc_status odbc_obj_connect(struct odbc_obj *obj)
  784. {
  785. int res;
  786. SQLINTEGER err;
  787. short int mlen;
  788. unsigned char msg[200], state[10];
  789. #ifdef NEEDTRACE
  790. SQLINTEGER enable = 1;
  791. char *tracefile = "/tmp/odbc.trace";
  792. #endif
  793. SQLHDBC con;
  794. long int negative_cache_expiration;
  795. ast_assert(obj->con == NULL);
  796. ast_debug(3, "Connecting %s(%p)\n", obj->parent->name, obj);
  797. /* Dont connect while server is marked as unreachable via negative_connection_cache */
  798. negative_cache_expiration = obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec;
  799. if (time(NULL) < negative_cache_expiration) {
  800. ast_log(LOG_WARNING, "Not connecting to %s. Negative connection cache for %ld seconds\n", obj->parent->name, negative_cache_expiration - time(NULL));
  801. return ODBC_FAIL;
  802. }
  803. res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &con);
  804. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  805. ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
  806. obj->parent->last_negative_connect = ast_tvnow();
  807. return ODBC_FAIL;
  808. }
  809. SQLSetConnectAttr(con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
  810. SQLSetConnectAttr(con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
  811. #ifdef NEEDTRACE
  812. SQLSetConnectAttr(con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
  813. SQLSetConnectAttr(con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
  814. #endif
  815. res = SQLConnect(con,
  816. (SQLCHAR *) obj->parent->dsn, SQL_NTS,
  817. (SQLCHAR *) obj->parent->username, SQL_NTS,
  818. (SQLCHAR *) obj->parent->password, SQL_NTS);
  819. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  820. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  821. obj->parent->last_negative_connect = ast_tvnow();
  822. ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
  823. if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) != SQL_SUCCESS) {
  824. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  825. ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
  826. }
  827. return ODBC_FAIL;
  828. } else {
  829. ast_debug(3, "res_odbc: Connected to %s [%s (%p)]\n", obj->parent->name, obj->parent->dsn, obj);
  830. }
  831. obj->con = con;
  832. return ODBC_SUCCESS;
  833. }
  834. /*!
  835. * \internal
  836. * \brief Implements the channels provider.
  837. */
  838. static int data_odbc_provider_handler(const struct ast_data_search *search,
  839. struct ast_data *root)
  840. {
  841. struct ao2_iterator aoi;
  842. struct odbc_class *class;
  843. struct ast_data *data_odbc_class, *data_odbc_connections;
  844. struct ast_data *enum_node;
  845. aoi = ao2_iterator_init(class_container, 0);
  846. while ((class = ao2_iterator_next(&aoi))) {
  847. data_odbc_class = ast_data_add_node(root, "class");
  848. if (!data_odbc_class) {
  849. ao2_ref(class, -1);
  850. continue;
  851. }
  852. ast_data_add_structure(odbc_class, data_odbc_class, class);
  853. data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
  854. if (!data_odbc_connections) {
  855. ao2_ref(class, -1);
  856. continue;
  857. }
  858. /* isolation */
  859. enum_node = ast_data_add_node(data_odbc_class, "isolation");
  860. if (!enum_node) {
  861. ao2_ref(class, -1);
  862. continue;
  863. }
  864. ast_data_add_int(enum_node, "value", class->isolation);
  865. ast_data_add_str(enum_node, "text", ast_odbc_isolation2text(class->isolation));
  866. ao2_ref(class, -1);
  867. if (!ast_data_search_match(search, data_odbc_class)) {
  868. ast_data_remove_node(root, data_odbc_class);
  869. }
  870. }
  871. ao2_iterator_destroy(&aoi);
  872. return 0;
  873. }
  874. /*!
  875. * \internal
  876. * \brief /asterisk/res/odbc/listprovider.
  877. */
  878. static const struct ast_data_handler odbc_provider = {
  879. .version = AST_DATA_HANDLER_VERSION,
  880. .get = data_odbc_provider_handler
  881. };
  882. static const struct ast_data_entry odbc_providers[] = {
  883. AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
  884. };
  885. static int reload(void)
  886. {
  887. struct odbc_cache_tables *table;
  888. struct odbc_class *class;
  889. struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
  890. /* First, mark all to be purged */
  891. while ((class = ao2_iterator_next(&aoi))) {
  892. class->delme = 1;
  893. ao2_ref(class, -1);
  894. }
  895. ao2_iterator_destroy(&aoi);
  896. load_odbc_config();
  897. aoi = ao2_iterator_init(class_container, 0);
  898. while ((class = ao2_iterator_next(&aoi))) {
  899. if (class->delme) {
  900. ao2_unlink(class_container, class);
  901. }
  902. ao2_ref(class, -1);
  903. }
  904. ao2_iterator_destroy(&aoi);
  905. /* Empty the cache; it will get rebuilt the next time the tables are needed. */
  906. AST_RWLIST_WRLOCK(&odbc_tables);
  907. while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
  908. destroy_table_cache(table);
  909. }
  910. AST_RWLIST_UNLOCK(&odbc_tables);
  911. return 0;
  912. }
  913. static int unload_module(void)
  914. {
  915. /* Prohibit unloading */
  916. return -1;
  917. }
  918. static int load_module(void)
  919. {
  920. class_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, ao2_match_by_addr);
  921. if (!class_container)
  922. return AST_MODULE_LOAD_DECLINE;
  923. if (load_odbc_config() == -1)
  924. return AST_MODULE_LOAD_DECLINE;
  925. ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
  926. ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
  927. return AST_MODULE_LOAD_SUCCESS;
  928. }
  929. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
  930. .support_level = AST_MODULE_SUPPORT_CORE,
  931. .load = load_module,
  932. .unload = unload_module,
  933. .reload = reload,
  934. .load_pri = AST_MODPRI_REALTIME_DEPEND,
  935. );