res_odbc.c 61 KB

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