res_odbc.c 61 KB

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