res_odbc.c 61 KB

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