res_odbc.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. /*** MODULEINFO
  32. <depend>generic_odbc</depend>
  33. <depend>ltdl</depend>
  34. <support_level>core</support_level>
  35. ***/
  36. #include "asterisk.h"
  37. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  38. #include "asterisk/file.h"
  39. #include "asterisk/channel.h"
  40. #include "asterisk/config.h"
  41. #include "asterisk/pbx.h"
  42. #include "asterisk/module.h"
  43. #include "asterisk/cli.h"
  44. #include "asterisk/lock.h"
  45. #include "asterisk/res_odbc.h"
  46. #include "asterisk/time.h"
  47. #include "asterisk/astobj2.h"
  48. #include "asterisk/app.h"
  49. #include "asterisk/strings.h"
  50. #include "asterisk/threadstorage.h"
  51. #include "asterisk/data.h"
  52. /*** DOCUMENTATION
  53. <function name="ODBC" language="en_US">
  54. <synopsis>
  55. Controls ODBC transaction properties.
  56. </synopsis>
  57. <syntax>
  58. <parameter name="property" required="true">
  59. <enumlist>
  60. <enum name="transaction">
  61. <para>Gets or sets the active transaction ID. If set, and the transaction ID does not
  62. exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
  63. </enum>
  64. <enum name="forcecommit">
  65. <para>Controls whether a transaction will be automatically committed when the channel
  66. hangs up. Defaults to false. If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
  67. the property will be applied to that ID, otherwise to the current active ID.</para>
  68. </enum>
  69. <enum name="isolation">
  70. <para>Controls the data isolation on uncommitted transactions. May be one of the
  71. following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
  72. <literal>repeatable_read</literal>, or <literal>serializable</literal>. Defaults to the
  73. database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
  74. if not specified. If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
  75. applied to that ID, otherwise the current active ID.</para>
  76. </enum>
  77. </enumlist>
  78. </parameter>
  79. <parameter name="argument" required="false" />
  80. </syntax>
  81. <description>
  82. <para>The ODBC() function allows setting several properties to influence how a connected
  83. database processes transactions.</para>
  84. </description>
  85. </function>
  86. <application name="ODBC_Commit" language="en_US">
  87. <synopsis>
  88. Commits a currently open database transaction.
  89. </synopsis>
  90. <syntax>
  91. <parameter name="transaction ID" required="no" />
  92. </syntax>
  93. <description>
  94. <para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
  95. or the current active transaction, if not specified.</para>
  96. </description>
  97. </application>
  98. <application name="ODBC_Rollback" language="en_US">
  99. <synopsis>
  100. Rollback a currently open database transaction.
  101. </synopsis>
  102. <syntax>
  103. <parameter name="transaction ID" required="no" />
  104. </syntax>
  105. <description>
  106. <para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
  107. or the current active transaction, if not specified.</para>
  108. </description>
  109. </application>
  110. ***/
  111. struct odbc_class
  112. {
  113. AST_LIST_ENTRY(odbc_class) list;
  114. char name[80];
  115. char dsn[80];
  116. char *username;
  117. char *password;
  118. char *sanitysql;
  119. SQLHENV env;
  120. unsigned int haspool:1; /*!< Boolean - TDS databases need this */
  121. unsigned int delme:1; /*!< Purge the class */
  122. unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
  123. unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
  124. unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
  125. unsigned int limit; /*!< Maximum number of database handles we will allow */
  126. int count; /*!< Running count of pooled connections */
  127. unsigned int idlecheck; /*!< Recheck the connection if it is idle for this long (in seconds) */
  128. unsigned int conntimeout; /*!< Maximum time the connection process should take */
  129. /*! When a connection fails, cache that failure for how long? */
  130. struct timeval negative_connection_cache;
  131. /*! When a connection fails, when did that last occur? */
  132. struct timeval last_negative_connect;
  133. /*! List of handles associated with this class */
  134. struct ao2_container *obj_container;
  135. };
  136. static struct ao2_container *class_container;
  137. static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
  138. static odbc_status odbc_obj_connect(struct odbc_obj *obj);
  139. static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
  140. static int odbc_register_class(struct odbc_class *class, int connect);
  141. static void odbc_txn_free(void *data);
  142. static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
  143. AST_THREADSTORAGE(errors_buf);
  144. static struct ast_datastore_info txn_info = {
  145. .type = "ODBC_Transaction",
  146. .destroy = odbc_txn_free,
  147. };
  148. struct odbc_txn_frame {
  149. AST_LIST_ENTRY(odbc_txn_frame) list;
  150. struct ast_channel *owner;
  151. struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
  152. /*!\brief Is this record the current active transaction within the channel?
  153. * Note that the active flag is really only necessary for statements which
  154. * are triggered from the dialplan, as there isn't a direct correlation
  155. * between multiple statements. Applications wishing to use transactions
  156. * may simply perform each statement on the same odbc_obj, which keeps the
  157. * transaction persistent.
  158. */
  159. unsigned int active:1;
  160. unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
  161. unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
  162. char name[0]; /*!< Name of this transaction ID */
  163. };
  164. #define DATA_EXPORT_ODBC_CLASS(MEMBER) \
  165. MEMBER(odbc_class, name, AST_DATA_STRING) \
  166. MEMBER(odbc_class, dsn, AST_DATA_STRING) \
  167. MEMBER(odbc_class, username, AST_DATA_STRING) \
  168. MEMBER(odbc_class, password, AST_DATA_PASSWORD) \
  169. MEMBER(odbc_class, limit, AST_DATA_INTEGER) \
  170. MEMBER(odbc_class, count, AST_DATA_INTEGER) \
  171. MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
  172. AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
  173. static const char *isolation2text(int iso)
  174. {
  175. if (iso == SQL_TXN_READ_COMMITTED) {
  176. return "read_committed";
  177. } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
  178. return "read_uncommitted";
  179. } else if (iso == SQL_TXN_SERIALIZABLE) {
  180. return "serializable";
  181. } else if (iso == SQL_TXN_REPEATABLE_READ) {
  182. return "repeatable_read";
  183. } else {
  184. return "unknown";
  185. }
  186. }
  187. static int text2isolation(const char *txt)
  188. {
  189. if (strncasecmp(txt, "read_", 5) == 0) {
  190. if (strncasecmp(txt + 5, "c", 1) == 0) {
  191. return SQL_TXN_READ_COMMITTED;
  192. } else if (strncasecmp(txt + 5, "u", 1) == 0) {
  193. return SQL_TXN_READ_UNCOMMITTED;
  194. } else {
  195. return 0;
  196. }
  197. } else if (strncasecmp(txt, "ser", 3) == 0) {
  198. return SQL_TXN_SERIALIZABLE;
  199. } else if (strncasecmp(txt, "rep", 3) == 0) {
  200. return SQL_TXN_REPEATABLE_READ;
  201. } else {
  202. return 0;
  203. }
  204. }
  205. static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
  206. {
  207. struct ast_datastore *txn_store;
  208. AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
  209. struct odbc_txn_frame *txn = NULL;
  210. if (!chan && obj && obj->txf && obj->txf->owner) {
  211. chan = obj->txf->owner;
  212. } else if (!chan) {
  213. /* No channel == no transaction */
  214. return NULL;
  215. }
  216. ast_channel_lock(chan);
  217. if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
  218. oldlist = txn_store->data;
  219. } else {
  220. /* Need to create a new datastore */
  221. if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
  222. ast_log(LOG_ERROR, "Unable to allocate a new datastore. Cannot create a new transaction.\n");
  223. ast_channel_unlock(chan);
  224. return NULL;
  225. }
  226. if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
  227. ast_log(LOG_ERROR, "Unable to allocate datastore list head. Cannot create a new transaction.\n");
  228. ast_datastore_free(txn_store);
  229. ast_channel_unlock(chan);
  230. return NULL;
  231. }
  232. txn_store->data = oldlist;
  233. AST_LIST_HEAD_INIT(oldlist);
  234. ast_channel_datastore_add(chan, txn_store);
  235. }
  236. AST_LIST_LOCK(oldlist);
  237. ast_channel_unlock(chan);
  238. /* Scanning for an object is *fast*. Scanning for a name is much slower. */
  239. if (obj != NULL || active == 1) {
  240. AST_LIST_TRAVERSE(oldlist, txn, list) {
  241. if (txn->obj == obj || txn->active) {
  242. AST_LIST_UNLOCK(oldlist);
  243. return txn;
  244. }
  245. }
  246. }
  247. if (name != NULL) {
  248. AST_LIST_TRAVERSE(oldlist, txn, list) {
  249. if (!strcasecmp(txn->name, name)) {
  250. AST_LIST_UNLOCK(oldlist);
  251. return txn;
  252. }
  253. }
  254. }
  255. /* Nothing found, create one */
  256. if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
  257. struct odbc_txn_frame *otxn;
  258. strcpy(txn->name, name); /* SAFE */
  259. txn->obj = obj;
  260. txn->isolation = obj->parent->isolation;
  261. txn->forcecommit = obj->parent->forcecommit;
  262. txn->owner = chan;
  263. txn->active = 1;
  264. /* On creation, the txn becomes active, and all others inactive */
  265. AST_LIST_TRAVERSE(oldlist, otxn, list) {
  266. otxn->active = 0;
  267. }
  268. AST_LIST_INSERT_TAIL(oldlist, txn, list);
  269. obj->txf = txn;
  270. obj->tx = 1;
  271. }
  272. AST_LIST_UNLOCK(oldlist);
  273. return txn;
  274. }
  275. static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
  276. {
  277. if (!tx) {
  278. return NULL;
  279. }
  280. ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
  281. /* If we have an owner, disassociate */
  282. if (tx->owner) {
  283. struct ast_datastore *txn_store;
  284. AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
  285. ast_channel_lock(tx->owner);
  286. if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
  287. oldlist = txn_store->data;
  288. AST_LIST_LOCK(oldlist);
  289. AST_LIST_REMOVE(oldlist, tx, list);
  290. AST_LIST_UNLOCK(oldlist);
  291. }
  292. ast_channel_unlock(tx->owner);
  293. tx->owner = NULL;
  294. }
  295. if (tx->obj) {
  296. /* If we have any uncommitted transactions, they are handled when we release the object */
  297. struct odbc_obj *obj = tx->obj;
  298. /* Prevent recursion during destruction */
  299. tx->obj->txf = NULL;
  300. tx->obj = NULL;
  301. odbc_release_obj2(obj, tx);
  302. }
  303. ast_free(tx);
  304. return NULL;
  305. }
  306. static void odbc_txn_free(void *vdata)
  307. {
  308. struct odbc_txn_frame *tx;
  309. AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
  310. ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
  311. AST_LIST_LOCK(oldlist);
  312. while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
  313. release_transaction(tx);
  314. }
  315. AST_LIST_UNLOCK(oldlist);
  316. AST_LIST_HEAD_DESTROY(oldlist);
  317. ast_free(oldlist);
  318. }
  319. static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
  320. {
  321. struct ast_datastore *txn_store;
  322. AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
  323. struct odbc_txn_frame *active = NULL, *txn;
  324. if (!chan && tx && tx->owner) {
  325. chan = tx->owner;
  326. }
  327. ast_channel_lock(chan);
  328. if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
  329. ast_channel_unlock(chan);
  330. return -1;
  331. }
  332. oldlist = txn_store->data;
  333. AST_LIST_LOCK(oldlist);
  334. AST_LIST_TRAVERSE(oldlist, txn, list) {
  335. if (txn == tx) {
  336. txn->active = 1;
  337. active = txn;
  338. } else {
  339. txn->active = 0;
  340. }
  341. }
  342. AST_LIST_UNLOCK(oldlist);
  343. ast_channel_unlock(chan);
  344. return active ? 0 : -1;
  345. }
  346. static void odbc_class_destructor(void *data)
  347. {
  348. struct odbc_class *class = data;
  349. /* Due to refcounts, we can safely assume that any objects with a reference
  350. * to us will prevent our destruction, so we don't need to worry about them.
  351. */
  352. if (class->username) {
  353. ast_free(class->username);
  354. }
  355. if (class->password) {
  356. ast_free(class->password);
  357. }
  358. if (class->sanitysql) {
  359. ast_free(class->sanitysql);
  360. }
  361. ao2_ref(class->obj_container, -1);
  362. SQLFreeHandle(SQL_HANDLE_ENV, class->env);
  363. }
  364. static int null_hash_fn(const void *obj, const int flags)
  365. {
  366. return 0;
  367. }
  368. static void odbc_obj_destructor(void *data)
  369. {
  370. struct odbc_obj *obj = data;
  371. struct odbc_class *class = obj->parent;
  372. obj->parent = NULL;
  373. odbc_obj_disconnect(obj);
  374. ast_mutex_destroy(&obj->lock);
  375. ao2_ref(class, -1);
  376. }
  377. static void destroy_table_cache(struct odbc_cache_tables *table) {
  378. struct odbc_cache_columns *col;
  379. ast_debug(1, "Destroying table cache for %s\n", table->table);
  380. AST_RWLIST_WRLOCK(&table->columns);
  381. while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
  382. ast_free(col);
  383. }
  384. AST_RWLIST_UNLOCK(&table->columns);
  385. AST_RWLIST_HEAD_DESTROY(&table->columns);
  386. ast_free(table);
  387. }
  388. /*!
  389. * \brief Find or create an entry describing the table specified.
  390. * \param database Name of an ODBC class on which to query the table
  391. * \param tablename Tablename to describe
  392. * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
  393. * When a structure is returned, the contained columns list will be
  394. * rdlock'ed, to ensure that it will be retained in memory.
  395. * \since 1.6.1
  396. */
  397. struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
  398. {
  399. struct odbc_cache_tables *tableptr;
  400. struct odbc_cache_columns *entry;
  401. char columnname[80];
  402. SQLLEN sqlptr;
  403. SQLHSTMT stmt = NULL;
  404. int res = 0, error = 0, try = 0;
  405. struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
  406. AST_RWLIST_RDLOCK(&odbc_tables);
  407. AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
  408. if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
  409. break;
  410. }
  411. }
  412. if (tableptr) {
  413. AST_RWLIST_RDLOCK(&tableptr->columns);
  414. AST_RWLIST_UNLOCK(&odbc_tables);
  415. if (obj) {
  416. ast_odbc_release_obj(obj);
  417. }
  418. return tableptr;
  419. }
  420. if (!obj) {
  421. ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
  422. AST_RWLIST_UNLOCK(&odbc_tables);
  423. return NULL;
  424. }
  425. /* Table structure not already cached; build it now. */
  426. ast_mutex_lock(&obj->lock);
  427. do {
  428. res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
  429. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  430. if (try == 0) {
  431. try = 1;
  432. ast_odbc_sanity_check(obj);
  433. continue;
  434. }
  435. ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
  436. break;
  437. }
  438. res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
  439. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  440. if (try == 0) {
  441. try = 1;
  442. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  443. ast_odbc_sanity_check(obj);
  444. continue;
  445. }
  446. ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
  447. break;
  448. }
  449. if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
  450. ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
  451. break;
  452. }
  453. tableptr->connection = (char *)tableptr + sizeof(*tableptr);
  454. tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
  455. strcpy(tableptr->connection, database); /* SAFE */
  456. strcpy(tableptr->table, tablename); /* SAFE */
  457. AST_RWLIST_HEAD_INIT(&(tableptr->columns));
  458. while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
  459. SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
  460. if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
  461. ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
  462. error = 1;
  463. break;
  464. }
  465. entry->name = (char *)entry + sizeof(*entry);
  466. strcpy(entry->name, columnname);
  467. SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
  468. SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
  469. SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
  470. SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
  471. SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
  472. SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
  473. /* Specification states that the octenlen should be the maximum number of bytes
  474. * returned in a char or binary column, but it seems that some drivers just set
  475. * it to NULL. (Bad Postgres! No biscuit!) */
  476. if (entry->octetlen == 0) {
  477. entry->octetlen = entry->size;
  478. }
  479. ast_verb(10, "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);
  480. /* Insert column info into column list */
  481. AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
  482. }
  483. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  484. AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
  485. AST_RWLIST_RDLOCK(&(tableptr->columns));
  486. break;
  487. } while (1);
  488. ast_mutex_unlock(&obj->lock);
  489. AST_RWLIST_UNLOCK(&odbc_tables);
  490. if (error) {
  491. destroy_table_cache(tableptr);
  492. tableptr = NULL;
  493. }
  494. if (obj) {
  495. ast_odbc_release_obj(obj);
  496. }
  497. return tableptr;
  498. }
  499. struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
  500. {
  501. struct odbc_cache_columns *col;
  502. AST_RWLIST_TRAVERSE(&table->columns, col, list) {
  503. if (strcasecmp(col->name, colname) == 0) {
  504. return col;
  505. }
  506. }
  507. return NULL;
  508. }
  509. int ast_odbc_clear_cache(const char *database, const char *tablename)
  510. {
  511. struct odbc_cache_tables *tableptr;
  512. AST_RWLIST_WRLOCK(&odbc_tables);
  513. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
  514. if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
  515. AST_LIST_REMOVE_CURRENT(list);
  516. destroy_table_cache(tableptr);
  517. break;
  518. }
  519. }
  520. AST_RWLIST_TRAVERSE_SAFE_END
  521. AST_RWLIST_UNLOCK(&odbc_tables);
  522. return tableptr ? 0 : -1;
  523. }
  524. SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
  525. {
  526. int attempt;
  527. SQLHSTMT stmt;
  528. ast_mutex_lock(&obj->lock);
  529. for (attempt = 0; attempt < 2; attempt++) {
  530. stmt = exec_cb(obj, data);
  531. if (stmt) {
  532. break;
  533. } else if (obj->tx) {
  534. ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
  535. break;
  536. } else if (attempt == 0) {
  537. ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
  538. }
  539. if (!ast_odbc_sanity_check(obj)) {
  540. break;
  541. }
  542. }
  543. ast_mutex_unlock(&obj->lock);
  544. return stmt;
  545. }
  546. SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
  547. {
  548. int res = 0, i, attempt;
  549. SQLINTEGER nativeerror=0, numfields=0;
  550. SQLSMALLINT diagbytes=0;
  551. unsigned char state[10], diagnostic[256];
  552. SQLHSTMT stmt;
  553. ast_mutex_lock(&obj->lock);
  554. for (attempt = 0; attempt < 2; attempt++) {
  555. /* This prepare callback may do more than just prepare -- it may also
  556. * bind parameters, bind results, etc. The real key, here, is that
  557. * when we disconnect, all handles become invalid for most databases.
  558. * We must therefore redo everything when we establish a new
  559. * connection. */
  560. stmt = prepare_cb(obj, data);
  561. if (stmt) {
  562. res = SQLExecute(stmt);
  563. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  564. if (res == SQL_ERROR) {
  565. SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  566. for (i = 0; i < numfields; i++) {
  567. SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  568. ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
  569. if (i > 10) {
  570. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  571. break;
  572. }
  573. }
  574. }
  575. if (obj->tx) {
  576. ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
  577. break;
  578. } else {
  579. ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
  580. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  581. stmt = NULL;
  582. obj->up = 0;
  583. /*
  584. * While this isn't the best way to try to correct an error, this won't automatically
  585. * fail when the statement handle invalidates.
  586. */
  587. if (!ast_odbc_sanity_check(obj)) {
  588. break;
  589. }
  590. continue;
  591. }
  592. } else {
  593. obj->last_used = ast_tvnow();
  594. }
  595. break;
  596. } else if (attempt == 0) {
  597. ast_odbc_sanity_check(obj);
  598. }
  599. }
  600. ast_mutex_unlock(&obj->lock);
  601. return stmt;
  602. }
  603. int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
  604. {
  605. int res = 0, i;
  606. SQLINTEGER nativeerror=0, numfields=0;
  607. SQLSMALLINT diagbytes=0;
  608. unsigned char state[10], diagnostic[256];
  609. ast_mutex_lock(&obj->lock);
  610. res = SQLExecute(stmt);
  611. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  612. if (res == SQL_ERROR) {
  613. SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  614. for (i = 0; i < numfields; i++) {
  615. SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  616. ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
  617. if (i > 10) {
  618. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  619. break;
  620. }
  621. }
  622. }
  623. } else {
  624. obj->last_used = ast_tvnow();
  625. }
  626. ast_mutex_unlock(&obj->lock);
  627. return res;
  628. }
  629. SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
  630. {
  631. SQLRETURN res;
  632. if (pmaxlen == 0) {
  633. if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
  634. ast_str_make_space(buf, *StrLen_or_Ind + 1);
  635. }
  636. } else if (pmaxlen > 0) {
  637. ast_str_make_space(buf, pmaxlen);
  638. }
  639. res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
  640. ast_str_update(*buf);
  641. return res;
  642. }
  643. int ast_odbc_sanity_check(struct odbc_obj *obj)
  644. {
  645. char *test_sql = "select 1";
  646. SQLHSTMT stmt;
  647. int res = 0;
  648. if (!ast_strlen_zero(obj->parent->sanitysql))
  649. test_sql = obj->parent->sanitysql;
  650. if (obj->up) {
  651. res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
  652. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  653. obj->up = 0;
  654. } else {
  655. res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
  656. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  657. obj->up = 0;
  658. } else {
  659. res = SQLExecute(stmt);
  660. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  661. obj->up = 0;
  662. }
  663. }
  664. }
  665. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  666. }
  667. if (!obj->up && !obj->tx) { /* Try to reconnect! */
  668. ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
  669. odbc_obj_disconnect(obj);
  670. odbc_obj_connect(obj);
  671. }
  672. return obj->up;
  673. }
  674. static int load_odbc_config(void)
  675. {
  676. static char *cfg = "res_odbc.conf";
  677. struct ast_config *config;
  678. struct ast_variable *v;
  679. char *cat;
  680. const char *dsn, *username, *password, *sanitysql;
  681. int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
  682. struct timeval ncache = { 0, 0 };
  683. unsigned int idlecheck;
  684. int preconnect = 0, res = 0;
  685. struct ast_flags config_flags = { 0 };
  686. struct odbc_class *new;
  687. config = ast_config_load(cfg, config_flags);
  688. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  689. ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
  690. return -1;
  691. }
  692. for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
  693. if (!strcasecmp(cat, "ENV")) {
  694. for (v = ast_variable_browse(config, cat); v; v = v->next) {
  695. setenv(v->name, v->value, 1);
  696. ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
  697. }
  698. } else {
  699. /* Reset all to defaults for each class of odbc connections */
  700. dsn = username = password = sanitysql = NULL;
  701. enabled = 1;
  702. preconnect = idlecheck = 0;
  703. pooling = 0;
  704. limit = 0;
  705. bse = 1;
  706. conntimeout = 10;
  707. forcecommit = 0;
  708. isolation = SQL_TXN_READ_COMMITTED;
  709. for (v = ast_variable_browse(config, cat); v; v = v->next) {
  710. if (!strcasecmp(v->name, "pooling")) {
  711. if (ast_true(v->value))
  712. pooling = 1;
  713. } else if (!strncasecmp(v->name, "share", 5)) {
  714. /* "shareconnections" is a little clearer in meaning than "pooling" */
  715. if (ast_false(v->value))
  716. pooling = 1;
  717. } else if (!strcasecmp(v->name, "limit")) {
  718. sscanf(v->value, "%30d", &limit);
  719. if (ast_true(v->value) && !limit) {
  720. ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Setting limit to 1023 for ODBC class '%s'.\n", v->value, cat);
  721. limit = 1023;
  722. } else if (ast_false(v->value)) {
  723. ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
  724. enabled = 0;
  725. break;
  726. }
  727. } else if (!strcasecmp(v->name, "idlecheck")) {
  728. sscanf(v->value, "%30u", &idlecheck);
  729. } else if (!strcasecmp(v->name, "enabled")) {
  730. enabled = ast_true(v->value);
  731. } else if (!strcasecmp(v->name, "pre-connect")) {
  732. preconnect = ast_true(v->value);
  733. } else if (!strcasecmp(v->name, "dsn")) {
  734. dsn = v->value;
  735. } else if (!strcasecmp(v->name, "username")) {
  736. username = v->value;
  737. } else if (!strcasecmp(v->name, "password")) {
  738. password = v->value;
  739. } else if (!strcasecmp(v->name, "sanitysql")) {
  740. sanitysql = v->value;
  741. } else if (!strcasecmp(v->name, "backslash_is_escape")) {
  742. bse = ast_true(v->value);
  743. } else if (!strcasecmp(v->name, "connect_timeout")) {
  744. if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
  745. ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
  746. conntimeout = 10;
  747. }
  748. } else if (!strcasecmp(v->name, "negative_connection_cache")) {
  749. double dncache;
  750. if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
  751. ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
  752. /* 5 minutes sounds like a reasonable default */
  753. ncache.tv_sec = 300;
  754. ncache.tv_usec = 0;
  755. } else {
  756. ncache.tv_sec = (int)dncache;
  757. ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
  758. }
  759. } else if (!strcasecmp(v->name, "forcecommit")) {
  760. forcecommit = ast_true(v->value);
  761. } else if (!strcasecmp(v->name, "isolation")) {
  762. if ((isolation = text2isolation(v->value)) == 0) {
  763. ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
  764. isolation = SQL_TXN_READ_COMMITTED;
  765. }
  766. }
  767. }
  768. if (enabled && !ast_strlen_zero(dsn)) {
  769. new = ao2_alloc(sizeof(*new), odbc_class_destructor);
  770. if (!new) {
  771. res = -1;
  772. break;
  773. }
  774. SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
  775. res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
  776. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  777. ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
  778. ao2_ref(new, -1);
  779. return res;
  780. }
  781. new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
  782. if (pooling) {
  783. new->haspool = pooling;
  784. if (limit) {
  785. new->limit = limit;
  786. } else {
  787. ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
  788. new->limit = 5;
  789. }
  790. }
  791. new->backslash_is_escape = bse ? 1 : 0;
  792. new->forcecommit = forcecommit ? 1 : 0;
  793. new->isolation = isolation;
  794. new->idlecheck = idlecheck;
  795. new->conntimeout = conntimeout;
  796. new->negative_connection_cache = ncache;
  797. if (cat)
  798. ast_copy_string(new->name, cat, sizeof(new->name));
  799. if (dsn)
  800. ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
  801. if (username && !(new->username = ast_strdup(username))) {
  802. ao2_ref(new, -1);
  803. break;
  804. }
  805. if (password && !(new->password = ast_strdup(password))) {
  806. ao2_ref(new, -1);
  807. break;
  808. }
  809. if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
  810. ao2_ref(new, -1);
  811. break;
  812. }
  813. odbc_register_class(new, preconnect);
  814. ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
  815. ao2_ref(new, -1);
  816. new = NULL;
  817. }
  818. }
  819. }
  820. ast_config_destroy(config);
  821. return res;
  822. }
  823. static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  824. {
  825. struct ao2_iterator aoi;
  826. struct odbc_class *class;
  827. struct odbc_obj *current;
  828. int length = 0;
  829. int which = 0;
  830. char *ret = NULL;
  831. switch (cmd) {
  832. case CLI_INIT:
  833. e->command = "odbc show";
  834. e->usage =
  835. "Usage: odbc show [class]\n"
  836. " List settings of a particular ODBC class or,\n"
  837. " if not specified, all classes.\n";
  838. return NULL;
  839. case CLI_GENERATE:
  840. if (a->pos != 2)
  841. return NULL;
  842. length = strlen(a->word);
  843. aoi = ao2_iterator_init(class_container, 0);
  844. while ((class = ao2_iterator_next(&aoi))) {
  845. if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
  846. ret = ast_strdup(class->name);
  847. }
  848. ao2_ref(class, -1);
  849. if (ret) {
  850. break;
  851. }
  852. }
  853. ao2_iterator_destroy(&aoi);
  854. if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
  855. ret = ast_strdup("all");
  856. }
  857. return ret;
  858. }
  859. ast_cli(a->fd, "\nODBC DSN Settings\n");
  860. ast_cli(a->fd, "-----------------\n\n");
  861. aoi = ao2_iterator_init(class_container, 0);
  862. while ((class = ao2_iterator_next(&aoi))) {
  863. if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
  864. int count = 0;
  865. char timestr[80];
  866. struct ast_tm tm;
  867. ast_localtime(&class->last_negative_connect, &tm, NULL);
  868. ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
  869. ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
  870. ast_cli(a->fd, " Last connection attempt: %s\n", timestr);
  871. if (class->haspool) {
  872. struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
  873. ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
  874. while ((current = ao2_iterator_next(&aoi2))) {
  875. ast_mutex_lock(&current->lock);
  876. #ifdef DEBUG_THREADS
  877. ast_cli(a->fd, " - Connection %d: %s (%s:%d %s)\n", ++count,
  878. current->used ? "in use" :
  879. current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
  880. current->file, current->lineno, current->function);
  881. #else
  882. ast_cli(a->fd, " - Connection %d: %s\n", ++count,
  883. current->used ? "in use" :
  884. current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
  885. #endif
  886. ast_mutex_unlock(&current->lock);
  887. ao2_ref(current, -1);
  888. }
  889. ao2_iterator_destroy(&aoi2);
  890. } else {
  891. /* Should only ever be one of these (unless there are transactions) */
  892. struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
  893. while ((current = ao2_iterator_next(&aoi2))) {
  894. ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->used ? "In use" :
  895. current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
  896. ao2_ref(current, -1);
  897. }
  898. ao2_iterator_destroy(&aoi2);
  899. }
  900. ast_cli(a->fd, "\n");
  901. }
  902. ao2_ref(class, -1);
  903. }
  904. ao2_iterator_destroy(&aoi);
  905. return CLI_SUCCESS;
  906. }
  907. static struct ast_cli_entry cli_odbc[] = {
  908. AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
  909. };
  910. static int odbc_register_class(struct odbc_class *class, int preconnect)
  911. {
  912. struct odbc_obj *obj;
  913. if (class) {
  914. ao2_link(class_container, class);
  915. /* I still have a reference in the caller, so a deref is NOT missing here. */
  916. if (preconnect) {
  917. /* Request and release builds a connection */
  918. obj = ast_odbc_request_obj(class->name, 0);
  919. if (obj) {
  920. ast_odbc_release_obj(obj);
  921. }
  922. }
  923. return 0;
  924. } else {
  925. ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
  926. return -1;
  927. }
  928. }
  929. static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
  930. {
  931. SQLINTEGER nativeerror=0, numfields=0;
  932. SQLSMALLINT diagbytes=0, i;
  933. unsigned char state[10], diagnostic[256];
  934. ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
  935. if (tx) {
  936. ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
  937. if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
  938. /* Handle possible transaction commit failure */
  939. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  940. for (i = 0; i < numfields; i++) {
  941. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  942. ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
  943. if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
  944. /* These codes mean that a commit failed and a transaction
  945. * is still active. We must rollback, or things will get
  946. * very, very weird for anybody using the handle next. */
  947. SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
  948. }
  949. if (i > 10) {
  950. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  951. break;
  952. }
  953. }
  954. }
  955. /* Transaction is done, reset autocommit */
  956. if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
  957. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  958. for (i = 0; i < numfields; i++) {
  959. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  960. ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
  961. if (i > 10) {
  962. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  963. break;
  964. }
  965. }
  966. }
  967. }
  968. #ifdef DEBUG_THREADS
  969. obj->file[0] = '\0';
  970. obj->function[0] = '\0';
  971. obj->lineno = 0;
  972. #endif
  973. /* For pooled connections, this frees the connection to be
  974. * reused. For non-pooled connections, it does nothing. */
  975. obj->used = 0;
  976. if (obj->txf) {
  977. /* Prevent recursion -- transaction is already closed out. */
  978. obj->txf->obj = NULL;
  979. obj->txf = release_transaction(obj->txf);
  980. }
  981. ao2_ref(obj, -1);
  982. }
  983. void ast_odbc_release_obj(struct odbc_obj *obj)
  984. {
  985. struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
  986. odbc_release_obj2(obj, tx);
  987. }
  988. int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
  989. {
  990. return obj->parent->backslash_is_escape;
  991. }
  992. static int commit_exec(struct ast_channel *chan, const char *data)
  993. {
  994. struct odbc_txn_frame *tx;
  995. SQLINTEGER nativeerror=0, numfields=0;
  996. SQLSMALLINT diagbytes=0, i;
  997. unsigned char state[10], diagnostic[256];
  998. if (ast_strlen_zero(data)) {
  999. tx = find_transaction(chan, NULL, NULL, 1);
  1000. } else {
  1001. tx = find_transaction(chan, NULL, data, 0);
  1002. }
  1003. pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
  1004. if (tx) {
  1005. if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
  1006. struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
  1007. ast_str_reset(errors);
  1008. /* Handle possible transaction commit failure */
  1009. SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1010. for (i = 0; i < numfields; i++) {
  1011. SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1012. ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
  1013. ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
  1014. if (i > 10) {
  1015. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1016. break;
  1017. }
  1018. }
  1019. pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
  1020. }
  1021. }
  1022. return 0;
  1023. }
  1024. static int rollback_exec(struct ast_channel *chan, const char *data)
  1025. {
  1026. struct odbc_txn_frame *tx;
  1027. SQLINTEGER nativeerror=0, numfields=0;
  1028. SQLSMALLINT diagbytes=0, i;
  1029. unsigned char state[10], diagnostic[256];
  1030. if (ast_strlen_zero(data)) {
  1031. tx = find_transaction(chan, NULL, NULL, 1);
  1032. } else {
  1033. tx = find_transaction(chan, NULL, data, 0);
  1034. }
  1035. pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
  1036. if (tx) {
  1037. if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
  1038. struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
  1039. ast_str_reset(errors);
  1040. /* Handle possible transaction commit failure */
  1041. SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1042. for (i = 0; i < numfields; i++) {
  1043. SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1044. ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
  1045. ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
  1046. if (i > 10) {
  1047. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1048. break;
  1049. }
  1050. }
  1051. pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
  1052. }
  1053. }
  1054. return 0;
  1055. }
  1056. static int aoro2_class_cb(void *obj, void *arg, int flags)
  1057. {
  1058. struct odbc_class *class = obj;
  1059. char *name = arg;
  1060. if (!strcmp(class->name, name) && !class->delme) {
  1061. return CMP_MATCH | CMP_STOP;
  1062. }
  1063. return 0;
  1064. }
  1065. #define USE_TX (void *)(long)1
  1066. #define NO_TX (void *)(long)2
  1067. #define EOR_TX (void *)(long)3
  1068. static int aoro2_obj_cb(void *vobj, void *arg, int flags)
  1069. {
  1070. struct odbc_obj *obj = vobj;
  1071. ast_mutex_lock(&obj->lock);
  1072. if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
  1073. obj->used = 1;
  1074. ast_mutex_unlock(&obj->lock);
  1075. return CMP_MATCH | CMP_STOP;
  1076. }
  1077. ast_mutex_unlock(&obj->lock);
  1078. return 0;
  1079. }
  1080. /* This function should only be called for shared connections. Otherwise, the lack of
  1081. * setting vobj->used breaks EOR_TX searching. For nonshared connections, use
  1082. * aoro2_obj_cb instead. */
  1083. static int aoro2_obj_notx_cb(void *vobj, void *arg, int flags)
  1084. {
  1085. struct odbc_obj *obj = vobj;
  1086. if (!obj->tx) {
  1087. return CMP_MATCH | CMP_STOP;
  1088. }
  1089. return 0;
  1090. }
  1091. struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
  1092. {
  1093. struct odbc_obj *obj = NULL;
  1094. struct odbc_class *class;
  1095. SQLINTEGER nativeerror=0, numfields=0;
  1096. SQLSMALLINT diagbytes=0, i;
  1097. unsigned char state[10], diagnostic[256];
  1098. if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
  1099. ast_debug(1, "Class '%s' not found!\n", name);
  1100. return NULL;
  1101. }
  1102. ast_assert(ao2_ref(class, 0) > 1);
  1103. if (class->haspool) {
  1104. /* Recycle connections before building another */
  1105. obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
  1106. if (obj) {
  1107. ast_assert(ao2_ref(obj, 0) > 1);
  1108. }
  1109. if (!obj && (ast_atomic_fetchadd_int(&class->count, +1) < class->limit) &&
  1110. (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
  1111. obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
  1112. if (!obj) {
  1113. class->count--;
  1114. ao2_ref(class, -1);
  1115. ast_debug(3, "Unable to allocate object\n");
  1116. ast_atomic_fetchadd_int(&class->count, -1);
  1117. return NULL;
  1118. }
  1119. ast_assert(ao2_ref(obj, 0) == 1);
  1120. ast_mutex_init(&obj->lock);
  1121. /* obj inherits the outstanding reference to class */
  1122. obj->parent = class;
  1123. class = NULL;
  1124. if (odbc_obj_connect(obj) == ODBC_FAIL) {
  1125. ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
  1126. ast_assert(ao2_ref(obj->parent, 0) > 0);
  1127. /* Because it was never within the container, we have to manually decrement the count here */
  1128. ast_atomic_fetchadd_int(&obj->parent->count, -1);
  1129. ao2_ref(obj, -1);
  1130. obj = NULL;
  1131. } else {
  1132. obj->used = 1;
  1133. ao2_link(obj->parent->obj_container, obj);
  1134. }
  1135. } else {
  1136. /* If construction fails due to the limit (or negative timecache), reverse our increment. */
  1137. if (!obj) {
  1138. ast_atomic_fetchadd_int(&class->count, -1);
  1139. }
  1140. /* Object is not constructed, so delete outstanding reference to class. */
  1141. ao2_ref(class, -1);
  1142. class = NULL;
  1143. }
  1144. if (!obj) {
  1145. return NULL;
  1146. }
  1147. ast_mutex_lock(&obj->lock);
  1148. if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
  1149. /* Ensure this connection has autocommit turned off. */
  1150. if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
  1151. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1152. for (i = 0; i < numfields; i++) {
  1153. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1154. ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
  1155. if (i > 10) {
  1156. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. }
  1162. } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
  1163. /* Non-pooled connections -- but must use a separate connection handle */
  1164. if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
  1165. ast_debug(1, "Object not found\n");
  1166. obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
  1167. if (!obj) {
  1168. ao2_ref(class, -1);
  1169. ast_debug(3, "Unable to allocate object\n");
  1170. return NULL;
  1171. }
  1172. ast_mutex_init(&obj->lock);
  1173. /* obj inherits the outstanding reference to class */
  1174. obj->parent = class;
  1175. class = NULL;
  1176. if (odbc_obj_connect(obj) == ODBC_FAIL) {
  1177. ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
  1178. ao2_ref(obj, -1);
  1179. obj = NULL;
  1180. } else {
  1181. obj->used = 1;
  1182. ao2_link(obj->parent->obj_container, obj);
  1183. ast_atomic_fetchadd_int(&obj->parent->count, +1);
  1184. }
  1185. }
  1186. if (!obj) {
  1187. return NULL;
  1188. }
  1189. ast_mutex_lock(&obj->lock);
  1190. if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
  1191. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1192. for (i = 0; i < numfields; i++) {
  1193. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1194. ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
  1195. if (i > 10) {
  1196. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1197. break;
  1198. }
  1199. }
  1200. }
  1201. } else {
  1202. /* Non-pooled connection: multiple modules can use the same connection. */
  1203. if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_notx_cb, NO_TX))) {
  1204. /* Object is not constructed, so delete outstanding reference to class. */
  1205. ast_assert(ao2_ref(class, 0) > 1);
  1206. ao2_ref(class, -1);
  1207. class = NULL;
  1208. } else {
  1209. /* No entry: build one */
  1210. if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
  1211. ast_assert(ao2_ref(class, 0) > 1);
  1212. ao2_ref(class, -1);
  1213. ast_debug(3, "Unable to allocate object\n");
  1214. return NULL;
  1215. }
  1216. ast_mutex_init(&obj->lock);
  1217. /* obj inherits the outstanding reference to class */
  1218. obj->parent = class;
  1219. class = NULL;
  1220. if (odbc_obj_connect(obj) == ODBC_FAIL) {
  1221. ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
  1222. ao2_ref(obj, -1);
  1223. obj = NULL;
  1224. } else {
  1225. ao2_link(obj->parent->obj_container, obj);
  1226. ast_assert(ao2_ref(obj, 0) > 1);
  1227. }
  1228. }
  1229. if (!obj) {
  1230. return NULL;
  1231. }
  1232. ast_mutex_lock(&obj->lock);
  1233. if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
  1234. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1235. for (i = 0; i < numfields; i++) {
  1236. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1237. ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
  1238. if (i > 10) {
  1239. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1240. break;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. ast_assert(obj != NULL);
  1246. /* Set the isolation property */
  1247. if (SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
  1248. SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1249. for (i = 0; i < numfields; i++) {
  1250. SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1251. ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
  1252. if (i > 10) {
  1253. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. if (ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
  1259. /* Check if this connection qualifies for reconnection, with negative connection cache time */
  1260. if (time(NULL) > obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec) {
  1261. odbc_obj_connect(obj);
  1262. }
  1263. } else if (ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
  1264. ast_odbc_sanity_check(obj);
  1265. } else if (obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
  1266. odbc_obj_connect(obj);
  1267. }
  1268. #ifdef DEBUG_THREADS
  1269. ast_copy_string(obj->file, file, sizeof(obj->file));
  1270. ast_copy_string(obj->function, function, sizeof(obj->function));
  1271. obj->lineno = lineno;
  1272. #endif
  1273. /* We had it locked because of the obj_connects we see here. */
  1274. ast_mutex_unlock(&obj->lock);
  1275. ast_assert(class == NULL);
  1276. ast_assert(ao2_ref(obj, 0) > 1);
  1277. return obj;
  1278. }
  1279. struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
  1280. {
  1281. struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
  1282. return _ast_odbc_request_obj2(name, flags, file, function, lineno);
  1283. }
  1284. struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
  1285. {
  1286. struct ast_datastore *txn_store;
  1287. AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
  1288. struct odbc_txn_frame *txn = NULL;
  1289. if (!chan) {
  1290. /* No channel == no transaction */
  1291. return NULL;
  1292. }
  1293. ast_channel_lock(chan);
  1294. if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
  1295. oldlist = txn_store->data;
  1296. } else {
  1297. ast_channel_unlock(chan);
  1298. return NULL;
  1299. }
  1300. AST_LIST_LOCK(oldlist);
  1301. ast_channel_unlock(chan);
  1302. AST_LIST_TRAVERSE(oldlist, txn, list) {
  1303. if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
  1304. AST_LIST_UNLOCK(oldlist);
  1305. return txn->obj;
  1306. }
  1307. }
  1308. AST_LIST_UNLOCK(oldlist);
  1309. return NULL;
  1310. }
  1311. static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
  1312. {
  1313. int res;
  1314. SQLINTEGER err;
  1315. short int mlen;
  1316. unsigned char msg[200], state[10];
  1317. SQLHDBC con;
  1318. /* Nothing to disconnect */
  1319. if (!obj->con) {
  1320. return ODBC_SUCCESS;
  1321. }
  1322. con = obj->con;
  1323. obj->con = NULL;
  1324. res = SQLDisconnect(con);
  1325. if (obj->parent) {
  1326. if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
  1327. ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
  1328. } else {
  1329. ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
  1330. }
  1331. }
  1332. if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con) == SQL_SUCCESS)) {
  1333. ast_log(LOG_DEBUG, "Database handle %p deallocated\n", con);
  1334. } else {
  1335. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  1336. ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
  1337. }
  1338. obj->up = 0;
  1339. return ODBC_SUCCESS;
  1340. }
  1341. static odbc_status odbc_obj_connect(struct odbc_obj *obj)
  1342. {
  1343. int res;
  1344. SQLINTEGER err;
  1345. short int mlen;
  1346. unsigned char msg[200], state[10];
  1347. #ifdef NEEDTRACE
  1348. SQLINTEGER enable = 1;
  1349. char *tracefile = "/tmp/odbc.trace";
  1350. #endif
  1351. SQLHDBC con;
  1352. if (obj->up) {
  1353. odbc_obj_disconnect(obj);
  1354. ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
  1355. } else {
  1356. ast_assert(obj->con == NULL);
  1357. ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
  1358. }
  1359. res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &con);
  1360. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1361. ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
  1362. obj->parent->last_negative_connect = ast_tvnow();
  1363. return ODBC_FAIL;
  1364. }
  1365. SQLSetConnectAttr(con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
  1366. SQLSetConnectAttr(con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
  1367. #ifdef NEEDTRACE
  1368. SQLSetConnectAttr(con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
  1369. SQLSetConnectAttr(con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
  1370. #endif
  1371. res = SQLConnect(con,
  1372. (SQLCHAR *) obj->parent->dsn, SQL_NTS,
  1373. (SQLCHAR *) obj->parent->username, SQL_NTS,
  1374. (SQLCHAR *) obj->parent->password, SQL_NTS);
  1375. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1376. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  1377. obj->parent->last_negative_connect = ast_tvnow();
  1378. ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
  1379. if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con) != SQL_SUCCESS)) {
  1380. SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
  1381. ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
  1382. }
  1383. return ODBC_FAIL;
  1384. } else {
  1385. ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
  1386. obj->up = 1;
  1387. obj->last_used = ast_tvnow();
  1388. }
  1389. obj->con = con;
  1390. return ODBC_SUCCESS;
  1391. }
  1392. static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  1393. {
  1394. AST_DECLARE_APP_ARGS(args,
  1395. AST_APP_ARG(property);
  1396. AST_APP_ARG(opt);
  1397. );
  1398. struct odbc_txn_frame *tx;
  1399. AST_STANDARD_APP_ARGS(args, data);
  1400. if (strcasecmp(args.property, "transaction") == 0) {
  1401. if ((tx = find_transaction(chan, NULL, NULL, 1))) {
  1402. ast_copy_string(buf, tx->name, len);
  1403. return 0;
  1404. }
  1405. } else if (strcasecmp(args.property, "isolation") == 0) {
  1406. if (!ast_strlen_zero(args.opt)) {
  1407. tx = find_transaction(chan, NULL, args.opt, 0);
  1408. } else {
  1409. tx = find_transaction(chan, NULL, NULL, 1);
  1410. }
  1411. if (tx) {
  1412. ast_copy_string(buf, isolation2text(tx->isolation), len);
  1413. return 0;
  1414. }
  1415. } else if (strcasecmp(args.property, "forcecommit") == 0) {
  1416. if (!ast_strlen_zero(args.opt)) {
  1417. tx = find_transaction(chan, NULL, args.opt, 0);
  1418. } else {
  1419. tx = find_transaction(chan, NULL, NULL, 1);
  1420. }
  1421. if (tx) {
  1422. ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
  1423. return 0;
  1424. }
  1425. }
  1426. return -1;
  1427. }
  1428. static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
  1429. {
  1430. AST_DECLARE_APP_ARGS(args,
  1431. AST_APP_ARG(property);
  1432. AST_APP_ARG(opt);
  1433. );
  1434. struct odbc_txn_frame *tx;
  1435. SQLINTEGER nativeerror=0, numfields=0;
  1436. SQLSMALLINT diagbytes=0, i;
  1437. unsigned char state[10], diagnostic[256];
  1438. AST_STANDARD_APP_ARGS(args, s);
  1439. if (strcasecmp(args.property, "transaction") == 0) {
  1440. /* Set active transaction */
  1441. struct odbc_obj *obj;
  1442. if ((tx = find_transaction(chan, NULL, value, 0))) {
  1443. mark_transaction_active(chan, tx);
  1444. } else {
  1445. /* No such transaction, create one */
  1446. struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
  1447. if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
  1448. ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
  1449. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
  1450. return -1;
  1451. }
  1452. if (!(tx = find_transaction(chan, obj, value, 0))) {
  1453. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
  1454. return -1;
  1455. }
  1456. obj->tx = 1;
  1457. }
  1458. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
  1459. return 0;
  1460. } else if (strcasecmp(args.property, "forcecommit") == 0) {
  1461. /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
  1462. if (ast_strlen_zero(args.opt)) {
  1463. tx = find_transaction(chan, NULL, NULL, 1);
  1464. } else {
  1465. tx = find_transaction(chan, NULL, args.opt, 0);
  1466. }
  1467. if (!tx) {
  1468. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
  1469. return -1;
  1470. }
  1471. if (ast_true(value)) {
  1472. tx->forcecommit = 1;
  1473. } else if (ast_false(value)) {
  1474. tx->forcecommit = 0;
  1475. } else {
  1476. ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
  1477. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
  1478. return -1;
  1479. }
  1480. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
  1481. return 0;
  1482. } else if (strcasecmp(args.property, "isolation") == 0) {
  1483. /* How do uncommitted transactions affect reads? */
  1484. int isolation = text2isolation(value);
  1485. if (ast_strlen_zero(args.opt)) {
  1486. tx = find_transaction(chan, NULL, NULL, 1);
  1487. } else {
  1488. tx = find_transaction(chan, NULL, args.opt, 0);
  1489. }
  1490. if (!tx) {
  1491. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
  1492. return -1;
  1493. }
  1494. if (isolation == 0) {
  1495. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
  1496. ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
  1497. } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
  1498. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
  1499. SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  1500. for (i = 0; i < numfields; i++) {
  1501. SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  1502. ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
  1503. if (i > 10) {
  1504. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  1505. break;
  1506. }
  1507. }
  1508. } else {
  1509. pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
  1510. tx->isolation = isolation;
  1511. }
  1512. return 0;
  1513. } else {
  1514. ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
  1515. return -1;
  1516. }
  1517. }
  1518. static struct ast_custom_function odbc_function = {
  1519. .name = "ODBC",
  1520. .read = acf_transaction_read,
  1521. .write = acf_transaction_write,
  1522. };
  1523. static const char * const app_commit = "ODBC_Commit";
  1524. static const char * const app_rollback = "ODBC_Rollback";
  1525. /*!
  1526. * \internal
  1527. * \brief Implements the channels provider.
  1528. */
  1529. static int data_odbc_provider_handler(const struct ast_data_search *search,
  1530. struct ast_data *root)
  1531. {
  1532. struct ao2_iterator aoi, aoi2;
  1533. struct odbc_class *class;
  1534. struct odbc_obj *current;
  1535. struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
  1536. struct ast_data *enum_node;
  1537. int count;
  1538. aoi = ao2_iterator_init(class_container, 0);
  1539. while ((class = ao2_iterator_next(&aoi))) {
  1540. data_odbc_class = ast_data_add_node(root, "class");
  1541. if (!data_odbc_class) {
  1542. ao2_ref(class, -1);
  1543. continue;
  1544. }
  1545. ast_data_add_structure(odbc_class, data_odbc_class, class);
  1546. if (!ao2_container_count(class->obj_container)) {
  1547. ao2_ref(class, -1);
  1548. continue;
  1549. }
  1550. data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
  1551. if (!data_odbc_connections) {
  1552. ao2_ref(class, -1);
  1553. continue;
  1554. }
  1555. ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
  1556. /* isolation */
  1557. enum_node = ast_data_add_node(data_odbc_class, "isolation");
  1558. if (!enum_node) {
  1559. ao2_ref(class, -1);
  1560. continue;
  1561. }
  1562. ast_data_add_int(enum_node, "value", class->isolation);
  1563. ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
  1564. count = 0;
  1565. aoi2 = ao2_iterator_init(class->obj_container, 0);
  1566. while ((current = ao2_iterator_next(&aoi2))) {
  1567. data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
  1568. if (!data_odbc_connection) {
  1569. ao2_ref(current, -1);
  1570. continue;
  1571. }
  1572. ast_mutex_lock(&current->lock);
  1573. ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
  1574. current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
  1575. ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
  1576. ast_mutex_unlock(&current->lock);
  1577. if (class->haspool) {
  1578. ast_data_add_int(data_odbc_connection, "number", ++count);
  1579. }
  1580. ao2_ref(current, -1);
  1581. }
  1582. ao2_iterator_destroy(&aoi2);
  1583. ao2_ref(class, -1);
  1584. if (!ast_data_search_match(search, data_odbc_class)) {
  1585. ast_data_remove_node(root, data_odbc_class);
  1586. }
  1587. }
  1588. ao2_iterator_destroy(&aoi);
  1589. return 0;
  1590. }
  1591. /*!
  1592. * \internal
  1593. * \brief /asterisk/res/odbc/listprovider.
  1594. */
  1595. static const struct ast_data_handler odbc_provider = {
  1596. .version = AST_DATA_HANDLER_VERSION,
  1597. .get = data_odbc_provider_handler
  1598. };
  1599. static const struct ast_data_entry odbc_providers[] = {
  1600. AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
  1601. };
  1602. static int reload(void)
  1603. {
  1604. struct odbc_cache_tables *table;
  1605. struct odbc_class *class;
  1606. struct odbc_obj *current;
  1607. struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
  1608. /* First, mark all to be purged */
  1609. while ((class = ao2_iterator_next(&aoi))) {
  1610. class->delme = 1;
  1611. ao2_ref(class, -1);
  1612. }
  1613. ao2_iterator_destroy(&aoi);
  1614. load_odbc_config();
  1615. /* Purge remaining classes */
  1616. /* Note on how this works; this is a case of circular references, so we
  1617. * explicitly do NOT want to use a callback here (or we wind up in
  1618. * recursive hell).
  1619. *
  1620. * 1. Iterate through all the classes. Note that the classes will currently
  1621. * contain two classes of the same name, one of which is marked delme and
  1622. * will be purged when all remaining objects of the class are released, and
  1623. * the other, which was created above when we re-parsed the config file.
  1624. * 2. On each class, there is a reference held by the master container and
  1625. * a reference held by each connection object. There are two cases for
  1626. * destruction of the class, noted below. However, in all cases, all O-refs
  1627. * (references to objects) will first be freed, which will cause the C-refs
  1628. * (references to classes) to be decremented (but never to 0, because the
  1629. * class container still has a reference).
  1630. * a) If the class has outstanding objects, the C-ref by the class
  1631. * container will then be freed, which leaves only C-refs by any
  1632. * outstanding objects. When the final outstanding object is released
  1633. * (O-refs held by applications and dialplan functions), it will in turn
  1634. * free the final C-ref, causing class destruction.
  1635. * b) If the class has no outstanding objects, when the class container
  1636. * removes the final C-ref, the class will be destroyed.
  1637. */
  1638. aoi = ao2_iterator_init(class_container, 0);
  1639. while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
  1640. if (class->delme) {
  1641. struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
  1642. while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
  1643. ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
  1644. ao2_ref(current, -1); /* O-ref-- (by iterator) */
  1645. /* At this point, either
  1646. * a) there's an outstanding O-ref, or
  1647. * b) the object has already been destroyed.
  1648. */
  1649. }
  1650. ao2_iterator_destroy(&aoi2);
  1651. ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
  1652. /* At this point, either
  1653. * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
  1654. * b) the last remaining C-ref is held by the iterator, which will be
  1655. * destroyed in the next step.
  1656. */
  1657. }
  1658. ao2_ref(class, -1); /* C-ref-- (by iterator) */
  1659. }
  1660. ao2_iterator_destroy(&aoi);
  1661. /* Empty the cache; it will get rebuilt the next time the tables are needed. */
  1662. AST_RWLIST_WRLOCK(&odbc_tables);
  1663. while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
  1664. destroy_table_cache(table);
  1665. }
  1666. AST_RWLIST_UNLOCK(&odbc_tables);
  1667. return 0;
  1668. }
  1669. static int unload_module(void)
  1670. {
  1671. /* Prohibit unloading */
  1672. return -1;
  1673. }
  1674. static int load_module(void)
  1675. {
  1676. if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
  1677. return AST_MODULE_LOAD_DECLINE;
  1678. if (load_odbc_config() == -1)
  1679. return AST_MODULE_LOAD_DECLINE;
  1680. ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
  1681. ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
  1682. ast_register_application_xml(app_commit, commit_exec);
  1683. ast_register_application_xml(app_rollback, rollback_exec);
  1684. ast_custom_function_register(&odbc_function);
  1685. ast_log(LOG_NOTICE, "res_odbc loaded.\n");
  1686. return 0;
  1687. }
  1688. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
  1689. .load = load_module,
  1690. .unload = unload_module,
  1691. .reload = reload,
  1692. .load_pri = AST_MODPRI_REALTIME_DEPEND,
  1693. );