res_odbc.c 60 KB

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