func_odbc.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (c) 2005, 2006 Tilghman Lesher
  5. * Copyright (c) 2008, 2009 Digium, Inc.
  6. *
  7. * Tilghman Lesher <func_odbc__200508@the-tilghman.com>
  8. *
  9. * See http://www.asterisk.org for more information about
  10. * the Asterisk project. Please do not directly contact
  11. * any of the maintainers of this project for assistance;
  12. * the project provides a web site, mailing lists and IRC
  13. * channels for your use.
  14. *
  15. * This program is free software, distributed under the terms of
  16. * the GNU General Public License Version 2. See the LICENSE file
  17. * at the top of the source tree.
  18. */
  19. /*!
  20. * \file
  21. *
  22. * \brief ODBC lookups
  23. *
  24. * \author Tilghman Lesher <func_odbc__200508@the-tilghman.com>
  25. *
  26. * \ingroup functions
  27. */
  28. /*** MODULEINFO
  29. <depend>res_odbc</depend>
  30. <support_level>core</support_level>
  31. ***/
  32. #include "asterisk.h"
  33. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  34. #include "asterisk/module.h"
  35. #include "asterisk/file.h"
  36. #include "asterisk/channel.h"
  37. #include "asterisk/pbx.h"
  38. #include "asterisk/config.h"
  39. #include "asterisk/res_odbc.h"
  40. #include "asterisk/app.h"
  41. #include "asterisk/cli.h"
  42. #include "asterisk/strings.h"
  43. /*** DOCUMENTATION
  44. <function name="ODBC_FETCH" language="en_US">
  45. <synopsis>
  46. Fetch a row from a multirow query.
  47. </synopsis>
  48. <syntax>
  49. <parameter name="result-id" required="true" />
  50. </syntax>
  51. <description>
  52. <para>For queries which are marked as mode=multirow, the original
  53. query returns a <replaceable>result-id</replaceable> from which results
  54. may be fetched. This function implements the actual fetch of the results.</para>
  55. <para>This also sets <variable>ODBC_FETCH_STATUS</variable>.</para>
  56. <variablelist>
  57. <variable name="ODBC_FETCH_STATUS">
  58. <value name="SUCESS">
  59. If rows are available.
  60. </value>
  61. <value name="FAILURE">
  62. If no rows are available.
  63. </value>
  64. </variable>
  65. </variablelist>
  66. </description>
  67. </function>
  68. <application name="ODBCFinish" language="en_US">
  69. <synopsis>
  70. Clear the resultset of a sucessful multirow query.
  71. </synopsis>
  72. <syntax>
  73. <parameter name="result-id" required="true" />
  74. </syntax>
  75. <description>
  76. <para>For queries which are marked as mode=multirow, this will clear
  77. any remaining rows of the specified resultset.</para>
  78. </description>
  79. </application>
  80. <function name="SQL_ESC" language="en_US">
  81. <synopsis>
  82. Escapes single ticks for use in SQL statements.
  83. </synopsis>
  84. <syntax>
  85. <parameter name="string" required="true" />
  86. </syntax>
  87. <description>
  88. <para>Used in SQL templates to escape data which may contain single ticks
  89. <literal>'</literal> which are otherwise used to delimit data.</para>
  90. <para>Example: SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'</para>
  91. </description>
  92. </function>
  93. ***/
  94. static char *config = "func_odbc.conf";
  95. enum odbc_option_flags {
  96. OPT_ESCAPECOMMAS = (1 << 0),
  97. OPT_MULTIROW = (1 << 1),
  98. };
  99. struct acf_odbc_query {
  100. AST_RWLIST_ENTRY(acf_odbc_query) list;
  101. char readhandle[5][30];
  102. char writehandle[5][30];
  103. char *sql_read;
  104. char *sql_write;
  105. char *sql_insert;
  106. unsigned int flags;
  107. int rowlimit;
  108. struct ast_custom_function *acf;
  109. };
  110. static void odbc_datastore_free(void *data);
  111. static const struct ast_datastore_info odbc_info = {
  112. .type = "FUNC_ODBC",
  113. .destroy = odbc_datastore_free,
  114. };
  115. /* For storing each result row */
  116. struct odbc_datastore_row {
  117. AST_LIST_ENTRY(odbc_datastore_row) list;
  118. char data[0];
  119. };
  120. /* For storing each result set */
  121. struct odbc_datastore {
  122. AST_LIST_HEAD(, odbc_datastore_row);
  123. char names[0];
  124. };
  125. static AST_RWLIST_HEAD_STATIC(queries, acf_odbc_query);
  126. static int resultcount = 0;
  127. AST_THREADSTORAGE(sql_buf);
  128. AST_THREADSTORAGE(sql2_buf);
  129. AST_THREADSTORAGE(coldata_buf);
  130. AST_THREADSTORAGE(colnames_buf);
  131. static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len);
  132. static void odbc_datastore_free(void *data)
  133. {
  134. struct odbc_datastore *result = data;
  135. struct odbc_datastore_row *row;
  136. if (!result) {
  137. return;
  138. }
  139. AST_LIST_LOCK(result);
  140. while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
  141. ast_free(row);
  142. }
  143. AST_LIST_UNLOCK(result);
  144. AST_LIST_HEAD_DESTROY(result);
  145. ast_free(result);
  146. }
  147. static SQLHSTMT generic_execute(struct odbc_obj *obj, void *data)
  148. {
  149. int res;
  150. char *sql = data;
  151. SQLHSTMT stmt;
  152. res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
  153. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  154. ast_log(LOG_WARNING, "SQL Alloc Handle failed (%d)!\n", res);
  155. return NULL;
  156. }
  157. res = SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
  158. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  159. if (res == SQL_ERROR) {
  160. int i;
  161. SQLINTEGER nativeerror=0, numfields=0;
  162. SQLSMALLINT diagbytes=0;
  163. unsigned char state[10], diagnostic[256];
  164. SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  165. for (i = 0; i < numfields; i++) {
  166. SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  167. ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
  168. if (i > 10) {
  169. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  170. break;
  171. }
  172. }
  173. }
  174. ast_log(LOG_WARNING, "SQL Exec Direct failed (%d)![%s]\n", res, sql);
  175. SQLCloseCursor(stmt);
  176. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  177. return NULL;
  178. }
  179. return stmt;
  180. }
  181. /*
  182. * Master control routine
  183. */
  184. static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
  185. {
  186. struct odbc_obj *obj = NULL;
  187. struct acf_odbc_query *query;
  188. char *t, varname[15];
  189. int i, dsn, bogus_chan = 0;
  190. int transactional = 0;
  191. AST_DECLARE_APP_ARGS(values,
  192. AST_APP_ARG(field)[100];
  193. );
  194. AST_DECLARE_APP_ARGS(args,
  195. AST_APP_ARG(field)[100];
  196. );
  197. SQLHSTMT stmt = NULL;
  198. SQLLEN rows=0;
  199. struct ast_str *buf = ast_str_thread_get(&sql_buf, 16);
  200. struct ast_str *insertbuf = ast_str_thread_get(&sql2_buf, 16);
  201. const char *status = "FAILURE";
  202. if (!buf || !insertbuf) {
  203. return -1;
  204. }
  205. AST_RWLIST_RDLOCK(&queries);
  206. AST_RWLIST_TRAVERSE(&queries, query, list) {
  207. if (!strcmp(query->acf->name, cmd)) {
  208. break;
  209. }
  210. }
  211. if (!query) {
  212. ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
  213. AST_RWLIST_UNLOCK(&queries);
  214. if (chan) {
  215. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  216. }
  217. return -1;
  218. }
  219. if (!chan) {
  220. if (!(chan = ast_dummy_channel_alloc())) {
  221. AST_RWLIST_UNLOCK(&queries);
  222. return -1;
  223. }
  224. bogus_chan = 1;
  225. }
  226. if (!bogus_chan) {
  227. ast_autoservice_start(chan);
  228. }
  229. ast_str_make_space(&buf, strlen(query->sql_write) * 2 + 300);
  230. /* We only get here if sql_write is set. sql_insert is optional however. */
  231. if (query->sql_insert) {
  232. ast_str_make_space(&insertbuf, strlen(query->sql_insert) * 2 + 300);
  233. }
  234. /* Parse our arguments */
  235. t = value ? ast_strdupa(value) : "";
  236. if (!s || !t) {
  237. ast_log(LOG_ERROR, "Out of memory\n");
  238. AST_RWLIST_UNLOCK(&queries);
  239. if (!bogus_chan) {
  240. ast_autoservice_stop(chan);
  241. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  242. } else {
  243. ast_channel_unref(chan);
  244. }
  245. return -1;
  246. }
  247. AST_STANDARD_APP_ARGS(args, s);
  248. for (i = 0; i < args.argc; i++) {
  249. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  250. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  251. }
  252. /* Parse values, just like arguments */
  253. AST_STANDARD_APP_ARGS(values, t);
  254. for (i = 0; i < values.argc; i++) {
  255. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  256. pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
  257. }
  258. /* Additionally set the value as a whole (but push an empty string if value is NULL) */
  259. pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
  260. ast_str_substitute_variables(&buf, 0, chan, query->sql_write);
  261. if (query->sql_insert) {
  262. ast_str_substitute_variables(&insertbuf, 0, chan, query->sql_insert);
  263. }
  264. if (bogus_chan) {
  265. chan = ast_channel_unref(chan);
  266. } else {
  267. /* Restore prior values */
  268. for (i = 0; i < args.argc; i++) {
  269. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  270. pbx_builtin_setvar_helper(chan, varname, NULL);
  271. }
  272. for (i = 0; i < values.argc; i++) {
  273. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  274. pbx_builtin_setvar_helper(chan, varname, NULL);
  275. }
  276. pbx_builtin_setvar_helper(chan, "VALUE", NULL);
  277. }
  278. /*!\note
  279. * Okay, this part is confusing. Transactions belong to a single database
  280. * handle. Therefore, when working with transactions, we CANNOT failover
  281. * to multiple DSNs. We MUST have a single handle all the way through the
  282. * transaction, or else we CANNOT enforce atomicity.
  283. */
  284. for (dsn = 0; dsn < 5; dsn++) {
  285. if (!ast_strlen_zero(query->writehandle[dsn])) {
  286. if (transactional) {
  287. /* This can only happen second time through or greater. */
  288. ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
  289. }
  290. if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn]))) {
  291. transactional = 1;
  292. } else {
  293. obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
  294. transactional = 0;
  295. }
  296. if (obj && (stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(buf)))) {
  297. break;
  298. }
  299. if (obj && !transactional) {
  300. ast_odbc_release_obj(obj);
  301. obj = NULL;
  302. }
  303. }
  304. }
  305. if (stmt) {
  306. SQLRowCount(stmt, &rows);
  307. SQLCloseCursor(stmt);
  308. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  309. if (rows != 0) {
  310. status = "SUCCESS";
  311. } else if (query->sql_insert) {
  312. if (obj && !transactional) {
  313. ast_odbc_release_obj(obj);
  314. obj = NULL;
  315. }
  316. for (transactional = 0, dsn = 0; dsn < 5; dsn++) {
  317. if (!ast_strlen_zero(query->writehandle[dsn])) {
  318. if (transactional) {
  319. /* This can only happen second time through or greater. */
  320. ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
  321. } else if (obj) {
  322. ast_odbc_release_obj(obj);
  323. obj = NULL;
  324. }
  325. if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn]))) {
  326. transactional = 1;
  327. } else {
  328. obj = ast_odbc_request_obj(query->writehandle[dsn], 0);
  329. transactional = 0;
  330. }
  331. if (obj) {
  332. stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(insertbuf));
  333. }
  334. }
  335. if (stmt) {
  336. status = "FAILOVER";
  337. SQLRowCount(stmt, &rows);
  338. SQLCloseCursor(stmt);
  339. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  340. break;
  341. }
  342. }
  343. }
  344. }
  345. AST_RWLIST_UNLOCK(&queries);
  346. /* Output the affected rows, for all cases. In the event of failure, we
  347. * flag this as -1 rows. Note that this is different from 0 affected rows
  348. * which would be the case if we succeeded in our query, but the values did
  349. * not change. */
  350. if (!bogus_chan) {
  351. snprintf(varname, sizeof(varname), "%d", (int)rows);
  352. pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
  353. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  354. }
  355. if (obj && !transactional) {
  356. ast_odbc_release_obj(obj);
  357. obj = NULL;
  358. }
  359. if (!bogus_chan) {
  360. ast_autoservice_stop(chan);
  361. }
  362. return 0;
  363. }
  364. static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
  365. {
  366. struct odbc_obj *obj = NULL;
  367. struct acf_odbc_query *query;
  368. char varname[15], rowcount[12] = "-1";
  369. struct ast_str *colnames = ast_str_thread_get(&colnames_buf, 16);
  370. int res, x, y, buflen = 0, escapecommas, rowlimit = 1, multirow = 0, dsn, bogus_chan = 0;
  371. AST_DECLARE_APP_ARGS(args,
  372. AST_APP_ARG(field)[100];
  373. );
  374. SQLHSTMT stmt = NULL;
  375. SQLSMALLINT colcount=0;
  376. SQLLEN indicator;
  377. SQLSMALLINT collength;
  378. struct odbc_datastore *resultset = NULL;
  379. struct odbc_datastore_row *row = NULL;
  380. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  381. const char *status = "FAILURE";
  382. if (!sql || !colnames) {
  383. if (chan) {
  384. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  385. }
  386. return -1;
  387. }
  388. ast_str_reset(colnames);
  389. AST_RWLIST_RDLOCK(&queries);
  390. AST_RWLIST_TRAVERSE(&queries, query, list) {
  391. if (!strcmp(query->acf->name, cmd)) {
  392. break;
  393. }
  394. }
  395. if (!query) {
  396. ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
  397. AST_RWLIST_UNLOCK(&queries);
  398. if (chan) {
  399. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  400. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  401. }
  402. return -1;
  403. }
  404. if (!chan) {
  405. if (!(chan = ast_dummy_channel_alloc())) {
  406. AST_RWLIST_UNLOCK(&queries);
  407. return -1;
  408. }
  409. bogus_chan = 1;
  410. }
  411. if (!bogus_chan) {
  412. ast_autoservice_start(chan);
  413. }
  414. AST_STANDARD_APP_ARGS(args, s);
  415. for (x = 0; x < args.argc; x++) {
  416. snprintf(varname, sizeof(varname), "ARG%d", x + 1);
  417. pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
  418. }
  419. ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
  420. if (bogus_chan) {
  421. chan = ast_channel_unref(chan);
  422. } else {
  423. /* Restore prior values */
  424. for (x = 0; x < args.argc; x++) {
  425. snprintf(varname, sizeof(varname), "ARG%d", x + 1);
  426. pbx_builtin_setvar_helper(chan, varname, NULL);
  427. }
  428. }
  429. /* Save these flags, so we can release the lock */
  430. escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
  431. if (!bogus_chan && ast_test_flag(query, OPT_MULTIROW)) {
  432. if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
  433. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  434. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  435. ast_autoservice_stop(chan);
  436. return -1;
  437. }
  438. AST_LIST_HEAD_INIT(resultset);
  439. if (query->rowlimit) {
  440. rowlimit = query->rowlimit;
  441. } else {
  442. rowlimit = INT_MAX;
  443. }
  444. multirow = 1;
  445. } else if (!bogus_chan) {
  446. if (query->rowlimit > 1) {
  447. rowlimit = query->rowlimit;
  448. if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
  449. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  450. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  451. ast_autoservice_stop(chan);
  452. return -1;
  453. }
  454. AST_LIST_HEAD_INIT(resultset);
  455. }
  456. }
  457. AST_RWLIST_UNLOCK(&queries);
  458. for (dsn = 0; dsn < 5; dsn++) {
  459. if (!ast_strlen_zero(query->readhandle[dsn])) {
  460. obj = ast_odbc_request_obj(query->readhandle[dsn], 0);
  461. if (obj) {
  462. stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql));
  463. }
  464. }
  465. if (stmt) {
  466. break;
  467. }
  468. if (obj) {
  469. ast_odbc_release_obj(obj);
  470. obj = NULL;
  471. }
  472. }
  473. if (!stmt) {
  474. ast_log(LOG_ERROR, "Unable to execute query [%s]\n", ast_str_buffer(sql));
  475. if (obj) {
  476. ast_odbc_release_obj(obj);
  477. obj = NULL;
  478. }
  479. if (!bogus_chan) {
  480. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  481. ast_autoservice_stop(chan);
  482. }
  483. odbc_datastore_free(resultset);
  484. return -1;
  485. }
  486. res = SQLNumResultCols(stmt, &colcount);
  487. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  488. ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
  489. SQLCloseCursor(stmt);
  490. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  491. ast_odbc_release_obj(obj);
  492. obj = NULL;
  493. if (!bogus_chan) {
  494. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  495. ast_autoservice_stop(chan);
  496. }
  497. odbc_datastore_free(resultset);
  498. return -1;
  499. }
  500. res = SQLFetch(stmt);
  501. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  502. int res1 = -1;
  503. if (res == SQL_NO_DATA) {
  504. ast_verb(4, "Found no rows [%s]\n", ast_str_buffer(sql));
  505. res1 = 0;
  506. buf[0] = '\0';
  507. ast_copy_string(rowcount, "0", sizeof(rowcount));
  508. status = "NODATA";
  509. } else {
  510. ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  511. status = "FETCHERROR";
  512. }
  513. SQLCloseCursor(stmt);
  514. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  515. ast_odbc_release_obj(obj);
  516. obj = NULL;
  517. if (!bogus_chan) {
  518. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  519. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  520. ast_autoservice_stop(chan);
  521. }
  522. odbc_datastore_free(resultset);
  523. return res1;
  524. }
  525. status = "SUCCESS";
  526. for (y = 0; y < rowlimit; y++) {
  527. buf[0] = '\0';
  528. for (x = 0; x < colcount; x++) {
  529. int i;
  530. struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
  531. char *ptrcoldata;
  532. if (!coldata) {
  533. odbc_datastore_free(resultset);
  534. SQLCloseCursor(stmt);
  535. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  536. ast_odbc_release_obj(obj);
  537. obj = NULL;
  538. if (!bogus_chan) {
  539. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  540. ast_autoservice_stop(chan);
  541. }
  542. return -1;
  543. }
  544. if (y == 0) {
  545. char colname[256];
  546. SQLULEN maxcol = 0;
  547. res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
  548. ast_debug(3, "Got collength of %d and maxcol of %d for column '%s' (offset %d)\n", (int)collength, (int)maxcol, colname, x);
  549. if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
  550. snprintf(colname, sizeof(colname), "field%d", x);
  551. }
  552. ast_str_make_space(&coldata, maxcol + 1);
  553. if (ast_str_strlen(colnames)) {
  554. ast_str_append(&colnames, 0, ",");
  555. }
  556. ast_str_append_escapecommas(&colnames, 0, colname, sizeof(colname));
  557. if (resultset) {
  558. void *tmp = ast_realloc(resultset, sizeof(*resultset) + ast_str_strlen(colnames) + 1);
  559. if (!tmp) {
  560. ast_log(LOG_ERROR, "No space for a new resultset?\n");
  561. odbc_datastore_free(resultset);
  562. SQLCloseCursor(stmt);
  563. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  564. ast_odbc_release_obj(obj);
  565. obj = NULL;
  566. if (!bogus_chan) {
  567. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  568. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  569. ast_autoservice_stop(chan);
  570. }
  571. return -1;
  572. }
  573. resultset = tmp;
  574. strcpy((char *)resultset + sizeof(*resultset), ast_str_buffer(colnames));
  575. }
  576. }
  577. buflen = strlen(buf);
  578. res = ast_odbc_ast_str_SQLGetData(&coldata, -1, stmt, x + 1, SQL_CHAR, &indicator);
  579. if (indicator == SQL_NULL_DATA) {
  580. ast_debug(3, "Got NULL data\n");
  581. ast_str_reset(coldata);
  582. res = SQL_SUCCESS;
  583. }
  584. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  585. ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", ast_str_buffer(sql));
  586. y = -1;
  587. buf[0] = '\0';
  588. goto end_acf_read;
  589. }
  590. ast_debug(2, "Got coldata of '%s'\n", ast_str_buffer(coldata));
  591. if (x) {
  592. buf[buflen++] = ',';
  593. }
  594. /* Copy data, encoding '\' and ',' for the argument parser */
  595. ptrcoldata = ast_str_buffer(coldata);
  596. for (i = 0; i < ast_str_strlen(coldata); i++) {
  597. if (escapecommas && (ptrcoldata[i] == '\\' || ptrcoldata[i] == ',')) {
  598. buf[buflen++] = '\\';
  599. }
  600. buf[buflen++] = ptrcoldata[i];
  601. if (buflen >= len - 2) {
  602. break;
  603. }
  604. if (ptrcoldata[i] == '\0') {
  605. break;
  606. }
  607. }
  608. buf[buflen] = '\0';
  609. ast_debug(2, "buf is now set to '%s'\n", buf);
  610. }
  611. ast_debug(2, "buf is now set to '%s'\n", buf);
  612. if (resultset) {
  613. row = ast_calloc(1, sizeof(*row) + buflen + 1);
  614. if (!row) {
  615. ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
  616. status = "MEMERROR";
  617. goto end_acf_read;
  618. }
  619. strcpy((char *)row + sizeof(*row), buf);
  620. AST_LIST_INSERT_TAIL(resultset, row, list);
  621. /* Get next row */
  622. res = SQLFetch(stmt);
  623. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  624. if (res != SQL_NO_DATA) {
  625. ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  626. }
  627. /* Number of rows in the resultset */
  628. y++;
  629. break;
  630. }
  631. }
  632. }
  633. end_acf_read:
  634. if (!bogus_chan) {
  635. snprintf(rowcount, sizeof(rowcount), "%d", y);
  636. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  637. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  638. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", ast_str_buffer(colnames));
  639. if (resultset) {
  640. struct ast_datastore *odbc_store;
  641. if (multirow) {
  642. int uid;
  643. uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
  644. snprintf(buf, len, "%d", uid);
  645. } else {
  646. /* Name of the query is name of the resultset */
  647. ast_copy_string(buf, cmd, len);
  648. /* If there's one with the same name already, free it */
  649. ast_channel_lock(chan);
  650. if ((odbc_store = ast_channel_datastore_find(chan, &odbc_info, buf))) {
  651. ast_channel_datastore_remove(chan, odbc_store);
  652. ast_datastore_free(odbc_store);
  653. }
  654. ast_channel_unlock(chan);
  655. }
  656. odbc_store = ast_datastore_alloc(&odbc_info, buf);
  657. if (!odbc_store) {
  658. ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel. Results fail.\n");
  659. odbc_datastore_free(resultset);
  660. SQLCloseCursor(stmt);
  661. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  662. ast_odbc_release_obj(obj);
  663. obj = NULL;
  664. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  665. ast_autoservice_stop(chan);
  666. return -1;
  667. }
  668. odbc_store->data = resultset;
  669. ast_channel_lock(chan);
  670. ast_channel_datastore_add(chan, odbc_store);
  671. ast_channel_unlock(chan);
  672. }
  673. }
  674. SQLCloseCursor(stmt);
  675. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  676. ast_odbc_release_obj(obj);
  677. obj = NULL;
  678. if (resultset && !multirow) {
  679. /* Fetch the first resultset */
  680. if (!acf_fetch(chan, "", buf, buf, len)) {
  681. buf[0] = '\0';
  682. }
  683. }
  684. if (!bogus_chan) {
  685. ast_autoservice_stop(chan);
  686. }
  687. return 0;
  688. }
  689. static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  690. {
  691. char *out = buf;
  692. for (; *data && out - buf < len; data++) {
  693. if (*data == '\'') {
  694. *out = '\'';
  695. out++;
  696. }
  697. *out++ = *data;
  698. }
  699. *out = '\0';
  700. return 0;
  701. }
  702. static struct ast_custom_function escape_function = {
  703. .name = "SQL_ESC",
  704. .read = acf_escape,
  705. .write = NULL,
  706. };
  707. static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  708. {
  709. struct ast_datastore *store;
  710. struct odbc_datastore *resultset;
  711. struct odbc_datastore_row *row;
  712. if (!chan) {
  713. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  714. return -1;
  715. }
  716. ast_channel_lock(chan);
  717. store = ast_channel_datastore_find(chan, &odbc_info, data);
  718. if (!store) {
  719. ast_channel_unlock(chan);
  720. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
  721. return -1;
  722. }
  723. resultset = store->data;
  724. AST_LIST_LOCK(resultset);
  725. row = AST_LIST_REMOVE_HEAD(resultset, list);
  726. AST_LIST_UNLOCK(resultset);
  727. if (!row) {
  728. /* Cleanup datastore */
  729. ast_channel_datastore_remove(chan, store);
  730. ast_datastore_free(store);
  731. ast_channel_unlock(chan);
  732. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
  733. return -1;
  734. }
  735. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
  736. ast_channel_unlock(chan);
  737. ast_copy_string(buf, row->data, len);
  738. ast_free(row);
  739. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "SUCCESS");
  740. return 0;
  741. }
  742. static struct ast_custom_function fetch_function = {
  743. .name = "ODBC_FETCH",
  744. .read = acf_fetch,
  745. .write = NULL,
  746. };
  747. static char *app_odbcfinish = "ODBCFinish";
  748. static int exec_odbcfinish(struct ast_channel *chan, const char *data)
  749. {
  750. struct ast_datastore *store;
  751. ast_channel_lock(chan);
  752. store = ast_channel_datastore_find(chan, &odbc_info, data);
  753. if (store) {
  754. ast_channel_datastore_remove(chan, store);
  755. ast_datastore_free(store);
  756. }
  757. ast_channel_unlock(chan);
  758. return 0;
  759. }
  760. static int free_acf_query(struct acf_odbc_query *query)
  761. {
  762. if (query) {
  763. if (query->acf) {
  764. if (query->acf->name)
  765. ast_free((char *)query->acf->name);
  766. ast_string_field_free_memory(query->acf);
  767. ast_free(query->acf);
  768. }
  769. ast_free(query->sql_read);
  770. ast_free(query->sql_write);
  771. ast_free(query->sql_insert);
  772. ast_free(query);
  773. }
  774. return 0;
  775. }
  776. static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
  777. {
  778. const char *tmp;
  779. const char *tmp2;
  780. int i;
  781. if (!cfg || !catg) {
  782. return EINVAL;
  783. }
  784. if (!(*query = ast_calloc(1, sizeof(**query)))) {
  785. return ENOMEM;
  786. }
  787. if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
  788. char *tmp2 = ast_strdupa(tmp);
  789. AST_DECLARE_APP_ARGS(writeconf,
  790. AST_APP_ARG(dsn)[5];
  791. );
  792. AST_STANDARD_APP_ARGS(writeconf, tmp2);
  793. for (i = 0; i < 5; i++) {
  794. if (!ast_strlen_zero(writeconf.dsn[i]))
  795. ast_copy_string((*query)->writehandle[i], writeconf.dsn[i], sizeof((*query)->writehandle[i]));
  796. }
  797. }
  798. if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
  799. char *tmp2 = ast_strdupa(tmp);
  800. AST_DECLARE_APP_ARGS(readconf,
  801. AST_APP_ARG(dsn)[5];
  802. );
  803. AST_STANDARD_APP_ARGS(readconf, tmp2);
  804. for (i = 0; i < 5; i++) {
  805. if (!ast_strlen_zero(readconf.dsn[i]))
  806. ast_copy_string((*query)->readhandle[i], readconf.dsn[i], sizeof((*query)->readhandle[i]));
  807. }
  808. } else {
  809. /* If no separate readhandle, then use the writehandle for reading */
  810. for (i = 0; i < 5; i++) {
  811. if (!ast_strlen_zero((*query)->writehandle[i]))
  812. ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
  813. }
  814. }
  815. if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")) ||
  816. (tmp2 = ast_variable_retrieve(cfg, catg, "read"))) {
  817. if (!tmp) {
  818. ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s. Please use 'readsql' instead.\n", catg);
  819. tmp = tmp2;
  820. }
  821. if (*tmp != '\0') { /* non-empty string */
  822. if (!((*query)->sql_read = ast_strdup(tmp))) {
  823. free_acf_query(*query);
  824. *query = NULL;
  825. return ENOMEM;
  826. }
  827. }
  828. }
  829. if ((*query)->sql_read && ast_strlen_zero((*query)->readhandle[0])) {
  830. free_acf_query(*query);
  831. *query = NULL;
  832. ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
  833. return EINVAL;
  834. }
  835. if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")) ||
  836. (tmp2 = ast_variable_retrieve(cfg, catg, "write"))) {
  837. if (!tmp) {
  838. ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s. Please use 'writesql' instead.\n", catg);
  839. tmp = tmp2;
  840. }
  841. if (*tmp != '\0') { /* non-empty string */
  842. if (!((*query)->sql_write = ast_strdup(tmp))) {
  843. free_acf_query(*query);
  844. *query = NULL;
  845. return ENOMEM;
  846. }
  847. }
  848. }
  849. if ((*query)->sql_write && ast_strlen_zero((*query)->writehandle[0])) {
  850. free_acf_query(*query);
  851. *query = NULL;
  852. ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
  853. return EINVAL;
  854. }
  855. if ((tmp = ast_variable_retrieve(cfg, catg, "insertsql"))) {
  856. if (*tmp != '\0') { /* non-empty string */
  857. if (!((*query)->sql_insert = ast_strdup(tmp))) {
  858. free_acf_query(*query);
  859. *query = NULL;
  860. return ENOMEM;
  861. }
  862. }
  863. }
  864. /* Allow escaping of embedded commas in fields to be turned off */
  865. ast_set_flag((*query), OPT_ESCAPECOMMAS);
  866. if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
  867. if (ast_false(tmp))
  868. ast_clear_flag((*query), OPT_ESCAPECOMMAS);
  869. }
  870. if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
  871. if (strcasecmp(tmp, "multirow") == 0)
  872. ast_set_flag((*query), OPT_MULTIROW);
  873. if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
  874. sscanf(tmp, "%30d", &((*query)->rowlimit));
  875. }
  876. (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
  877. if (!(*query)->acf) {
  878. free_acf_query(*query);
  879. *query = NULL;
  880. return ENOMEM;
  881. }
  882. if (ast_string_field_init((*query)->acf, 128)) {
  883. free_acf_query(*query);
  884. *query = NULL;
  885. return ENOMEM;
  886. }
  887. if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
  888. if (ast_asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg) < 0) {
  889. (*query)->acf->name = NULL;
  890. }
  891. } else {
  892. if (ast_asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg) < 0) {
  893. (*query)->acf->name = NULL;
  894. }
  895. }
  896. if (!(*query)->acf->name) {
  897. free_acf_query(*query);
  898. *query = NULL;
  899. return ENOMEM;
  900. }
  901. if ((tmp = ast_variable_retrieve(cfg, catg, "syntax")) && !ast_strlen_zero(tmp)) {
  902. ast_string_field_build((*query)->acf, syntax, "%s(%s)", (*query)->acf->name, tmp);
  903. } else {
  904. ast_string_field_build((*query)->acf, syntax, "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
  905. }
  906. if (ast_strlen_zero((*query)->acf->syntax)) {
  907. free_acf_query(*query);
  908. *query = NULL;
  909. return ENOMEM;
  910. }
  911. if ((tmp = ast_variable_retrieve(cfg, catg, "synopsis")) && !ast_strlen_zero(tmp)) {
  912. ast_string_field_set((*query)->acf, synopsis, tmp);
  913. } else {
  914. ast_string_field_set((*query)->acf, synopsis, "Runs the referenced query with the specified arguments");
  915. }
  916. if (ast_strlen_zero((*query)->acf->synopsis)) {
  917. free_acf_query(*query);
  918. *query = NULL;
  919. return ENOMEM;
  920. }
  921. if ((*query)->sql_read && (*query)->sql_write) {
  922. ast_string_field_build((*query)->acf, desc,
  923. "Runs the following query, as defined in func_odbc.conf, performing\n"
  924. "substitution of the arguments into the query as specified by ${ARG1},\n"
  925. "${ARG2}, ... ${ARGn}. When setting the function, the values are provided\n"
  926. "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
  927. "%s"
  928. "\nRead:\n%s\n\nWrite:\n%s%s%s",
  929. (*query)->sql_insert ?
  930. "If the write query affects no rows, the insert query will be\n"
  931. "performed.\n" : "",
  932. (*query)->sql_read,
  933. (*query)->sql_write,
  934. (*query)->sql_insert ? "\n\nInsert:\n" : "",
  935. (*query)->sql_insert ? (*query)->sql_insert : "");
  936. } else if ((*query)->sql_read) {
  937. ast_string_field_build((*query)->acf, desc,
  938. "Runs the following query, as defined in func_odbc.conf, performing\n"
  939. "substitution of the arguments into the query as specified by ${ARG1},\n"
  940. "${ARG2}, ... ${ARGn}. This function may only be read, not set.\n\nSQL:\n%s",
  941. (*query)->sql_read);
  942. } else if ((*query)->sql_write) {
  943. ast_string_field_build((*query)->acf, desc,
  944. "Runs the following query, as defined in func_odbc.conf, performing\n"
  945. "substitution of the arguments into the query as specified by ${ARG1},\n"
  946. "${ARG2}, ... ${ARGn}. The values are provided either in whole as\n"
  947. "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
  948. "This function may only be set.\n%s\nSQL:\n%s%s%s",
  949. (*query)->sql_insert ?
  950. "If the write query affects no rows, the insert query will be\n"
  951. "performed.\n" : "",
  952. (*query)->sql_write,
  953. (*query)->sql_insert ? "\n\nInsert:\n" : "",
  954. (*query)->sql_insert ? (*query)->sql_insert : "");
  955. } else {
  956. free_acf_query(*query);
  957. *query = NULL;
  958. ast_log(LOG_WARNING, "Section '%s' was found, but there was no SQL to execute. Ignoring.\n", catg);
  959. return EINVAL;
  960. }
  961. if (ast_strlen_zero((*query)->acf->desc)) {
  962. free_acf_query(*query);
  963. *query = NULL;
  964. return ENOMEM;
  965. }
  966. if ((*query)->sql_read) {
  967. (*query)->acf->read = acf_odbc_read;
  968. }
  969. if ((*query)->sql_write) {
  970. (*query)->acf->write = acf_odbc_write;
  971. }
  972. return 0;
  973. }
  974. static char *cli_odbc_read(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  975. {
  976. AST_DECLARE_APP_ARGS(args,
  977. AST_APP_ARG(field)[100];
  978. );
  979. struct ast_str *sql;
  980. char *char_args, varname[10];
  981. struct acf_odbc_query *query;
  982. struct ast_channel *chan;
  983. int i;
  984. switch (cmd) {
  985. case CLI_INIT:
  986. e->command = "odbc read";
  987. e->usage =
  988. "Usage: odbc read <name> <args> [exec]\n"
  989. " Evaluates the SQL provided in the ODBC function <name>, and\n"
  990. " optionally executes the function. This function is intended for\n"
  991. " testing purposes. Remember to quote arguments containing spaces.\n";
  992. return NULL;
  993. case CLI_GENERATE:
  994. if (a->pos == 2) {
  995. int wordlen = strlen(a->word), which = 0;
  996. /* Complete function name */
  997. AST_RWLIST_RDLOCK(&queries);
  998. AST_RWLIST_TRAVERSE(&queries, query, list) {
  999. if (!strncasecmp(query->acf->name, a->word, wordlen)) {
  1000. if (++which > a->n) {
  1001. char *res = ast_strdup(query->acf->name);
  1002. AST_RWLIST_UNLOCK(&queries);
  1003. return res;
  1004. }
  1005. }
  1006. }
  1007. AST_RWLIST_UNLOCK(&queries);
  1008. return NULL;
  1009. } else if (a->pos == 4) {
  1010. return a->n == 0 ? ast_strdup("exec") : NULL;
  1011. } else {
  1012. return NULL;
  1013. }
  1014. }
  1015. if (a->argc < 4 || a->argc > 5) {
  1016. return CLI_SHOWUSAGE;
  1017. }
  1018. sql = ast_str_thread_get(&sql_buf, 16);
  1019. if (!sql) {
  1020. return CLI_FAILURE;
  1021. }
  1022. AST_RWLIST_RDLOCK(&queries);
  1023. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1024. if (!strcmp(query->acf->name, a->argv[2])) {
  1025. break;
  1026. }
  1027. }
  1028. if (!query) {
  1029. ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
  1030. AST_RWLIST_UNLOCK(&queries);
  1031. return CLI_SHOWUSAGE;
  1032. }
  1033. if (!query->sql_read) {
  1034. ast_cli(a->fd, "The function %s has no readsql parameter.\n", a->argv[2]);
  1035. AST_RWLIST_UNLOCK(&queries);
  1036. return CLI_SUCCESS;
  1037. }
  1038. ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
  1039. /* Evaluate function */
  1040. char_args = ast_strdupa(a->argv[3]);
  1041. chan = ast_dummy_channel_alloc();
  1042. if (!chan) {
  1043. AST_RWLIST_UNLOCK(&queries);
  1044. return CLI_FAILURE;
  1045. }
  1046. AST_STANDARD_APP_ARGS(args, char_args);
  1047. for (i = 0; i < args.argc; i++) {
  1048. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  1049. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  1050. }
  1051. ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
  1052. chan = ast_channel_unref(chan);
  1053. if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
  1054. /* Execute the query */
  1055. struct odbc_obj *obj = NULL;
  1056. int dsn, executed = 0;
  1057. SQLHSTMT stmt;
  1058. int rows = 0, res, x;
  1059. SQLSMALLINT colcount = 0, collength;
  1060. SQLLEN indicator;
  1061. struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
  1062. char colname[256];
  1063. SQLULEN maxcol;
  1064. if (!coldata) {
  1065. AST_RWLIST_UNLOCK(&queries);
  1066. return CLI_SUCCESS;
  1067. }
  1068. for (dsn = 0; dsn < 5; dsn++) {
  1069. if (ast_strlen_zero(query->readhandle[dsn])) {
  1070. continue;
  1071. }
  1072. ast_debug(1, "Found handle %s\n", query->readhandle[dsn]);
  1073. if (!(obj = ast_odbc_request_obj(query->readhandle[dsn], 0))) {
  1074. continue;
  1075. }
  1076. ast_debug(1, "Got obj\n");
  1077. if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
  1078. ast_odbc_release_obj(obj);
  1079. obj = NULL;
  1080. continue;
  1081. }
  1082. executed = 1;
  1083. res = SQLNumResultCols(stmt, &colcount);
  1084. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1085. ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
  1086. SQLCloseCursor(stmt);
  1087. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  1088. ast_odbc_release_obj(obj);
  1089. obj = NULL;
  1090. AST_RWLIST_UNLOCK(&queries);
  1091. return CLI_SUCCESS;
  1092. }
  1093. res = SQLFetch(stmt);
  1094. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1095. SQLCloseCursor(stmt);
  1096. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1097. ast_odbc_release_obj(obj);
  1098. obj = NULL;
  1099. if (res == SQL_NO_DATA) {
  1100. ast_cli(a->fd, "Returned %d rows. Query executed on handle %d:%s [%s]\n", rows, dsn, query->readhandle[dsn], ast_str_buffer(sql));
  1101. break;
  1102. } else {
  1103. ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  1104. }
  1105. AST_RWLIST_UNLOCK(&queries);
  1106. return CLI_SUCCESS;
  1107. }
  1108. for (;;) {
  1109. for (x = 0; x < colcount; x++) {
  1110. maxcol = 0;
  1111. res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
  1112. if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
  1113. snprintf(colname, sizeof(colname), "field%d", x);
  1114. }
  1115. res = ast_odbc_ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
  1116. if (indicator == SQL_NULL_DATA) {
  1117. ast_str_set(&coldata, 0, "(nil)");
  1118. res = SQL_SUCCESS;
  1119. }
  1120. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1121. ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
  1122. SQLCloseCursor(stmt);
  1123. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1124. ast_odbc_release_obj(obj);
  1125. obj = NULL;
  1126. AST_RWLIST_UNLOCK(&queries);
  1127. return CLI_SUCCESS;
  1128. }
  1129. ast_cli(a->fd, "%-20.20s %s\n", colname, ast_str_buffer(coldata));
  1130. }
  1131. rows++;
  1132. /* Get next row */
  1133. res = SQLFetch(stmt);
  1134. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1135. break;
  1136. }
  1137. ast_cli(a->fd, "%-20.20s %s\n", "----------", "----------");
  1138. }
  1139. SQLCloseCursor(stmt);
  1140. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1141. ast_odbc_release_obj(obj);
  1142. obj = NULL;
  1143. ast_cli(a->fd, "Returned %d row%s. Query executed on handle %d [%s]\n", rows, rows == 1 ? "" : "s", dsn, query->readhandle[dsn]);
  1144. break;
  1145. }
  1146. if (obj) {
  1147. ast_odbc_release_obj(obj);
  1148. obj = NULL;
  1149. }
  1150. if (!executed) {
  1151. ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
  1152. }
  1153. } else { /* No execution, just print out the resulting SQL */
  1154. ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
  1155. }
  1156. AST_RWLIST_UNLOCK(&queries);
  1157. return CLI_SUCCESS;
  1158. }
  1159. static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1160. {
  1161. AST_DECLARE_APP_ARGS(values,
  1162. AST_APP_ARG(field)[100];
  1163. );
  1164. AST_DECLARE_APP_ARGS(args,
  1165. AST_APP_ARG(field)[100];
  1166. );
  1167. struct ast_str *sql;
  1168. char *char_args, *char_values, varname[10];
  1169. struct acf_odbc_query *query;
  1170. struct ast_channel *chan;
  1171. int i;
  1172. switch (cmd) {
  1173. case CLI_INIT:
  1174. e->command = "odbc write";
  1175. e->usage =
  1176. "Usage: odbc write <name> <args> <value> [exec]\n"
  1177. " Evaluates the SQL provided in the ODBC function <name>, and\n"
  1178. " optionally executes the function. This function is intended for\n"
  1179. " testing purposes. Remember to quote arguments containing spaces.\n";
  1180. return NULL;
  1181. case CLI_GENERATE:
  1182. if (a->pos == 2) {
  1183. int wordlen = strlen(a->word), which = 0;
  1184. /* Complete function name */
  1185. AST_RWLIST_RDLOCK(&queries);
  1186. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1187. if (!strncasecmp(query->acf->name, a->word, wordlen)) {
  1188. if (++which > a->n) {
  1189. char *res = ast_strdup(query->acf->name);
  1190. AST_RWLIST_UNLOCK(&queries);
  1191. return res;
  1192. }
  1193. }
  1194. }
  1195. AST_RWLIST_UNLOCK(&queries);
  1196. return NULL;
  1197. } else if (a->pos == 5) {
  1198. return a->n == 0 ? ast_strdup("exec") : NULL;
  1199. } else {
  1200. return NULL;
  1201. }
  1202. }
  1203. if (a->argc < 5 || a->argc > 6) {
  1204. return CLI_SHOWUSAGE;
  1205. }
  1206. sql = ast_str_thread_get(&sql_buf, 16);
  1207. if (!sql) {
  1208. return CLI_FAILURE;
  1209. }
  1210. AST_RWLIST_RDLOCK(&queries);
  1211. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1212. if (!strcmp(query->acf->name, a->argv[2])) {
  1213. break;
  1214. }
  1215. }
  1216. if (!query) {
  1217. ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
  1218. AST_RWLIST_UNLOCK(&queries);
  1219. return CLI_SHOWUSAGE;
  1220. }
  1221. if (!query->sql_write) {
  1222. ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
  1223. AST_RWLIST_UNLOCK(&queries);
  1224. return CLI_SUCCESS;
  1225. }
  1226. /* FIXME: The code below duplicates code found in acf_odbc_write but
  1227. * lacks the newer sql_insert additions. */
  1228. ast_str_make_space(&sql, strlen(query->sql_write) * 2 + 300);
  1229. /* Evaluate function */
  1230. char_args = ast_strdupa(a->argv[3]);
  1231. char_values = ast_strdupa(a->argv[4]);
  1232. chan = ast_dummy_channel_alloc();
  1233. if (!chan) {
  1234. AST_RWLIST_UNLOCK(&queries);
  1235. return CLI_FAILURE;
  1236. }
  1237. AST_STANDARD_APP_ARGS(args, char_args);
  1238. for (i = 0; i < args.argc; i++) {
  1239. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  1240. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  1241. }
  1242. /* Parse values, just like arguments */
  1243. AST_STANDARD_APP_ARGS(values, char_values);
  1244. for (i = 0; i < values.argc; i++) {
  1245. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  1246. pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
  1247. }
  1248. /* Additionally set the value as a whole (but push an empty string if value is NULL) */
  1249. pbx_builtin_pushvar_helper(chan, "VALUE", S_OR(a->argv[4], ""));
  1250. ast_str_substitute_variables(&sql, 0, chan, query->sql_write);
  1251. ast_debug(1, "SQL is %s\n", ast_str_buffer(sql));
  1252. chan = ast_channel_unref(chan);
  1253. if (a->argc == 6 && !strcmp(a->argv[5], "exec")) {
  1254. /* Execute the query */
  1255. struct odbc_obj *obj = NULL;
  1256. int dsn, executed = 0;
  1257. SQLHSTMT stmt;
  1258. SQLLEN rows = -1;
  1259. for (dsn = 0; dsn < 5; dsn++) {
  1260. if (ast_strlen_zero(query->writehandle[dsn])) {
  1261. continue;
  1262. }
  1263. if (!(obj = ast_odbc_request_obj(query->writehandle[dsn], 0))) {
  1264. continue;
  1265. }
  1266. if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
  1267. ast_odbc_release_obj(obj);
  1268. obj = NULL;
  1269. continue;
  1270. }
  1271. SQLRowCount(stmt, &rows);
  1272. SQLCloseCursor(stmt);
  1273. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1274. ast_odbc_release_obj(obj);
  1275. obj = NULL;
  1276. ast_cli(a->fd, "Affected %d rows. Query executed on handle %d [%s]\n", (int)rows, dsn, query->writehandle[dsn]);
  1277. executed = 1;
  1278. break;
  1279. }
  1280. if (!executed) {
  1281. ast_cli(a->fd, "Failed to execute query.\n");
  1282. }
  1283. } else { /* No execution, just print out the resulting SQL */
  1284. ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
  1285. }
  1286. AST_RWLIST_UNLOCK(&queries);
  1287. return CLI_SUCCESS;
  1288. }
  1289. static struct ast_cli_entry cli_func_odbc[] = {
  1290. AST_CLI_DEFINE(cli_odbc_write, "Test setting a func_odbc function"),
  1291. AST_CLI_DEFINE(cli_odbc_read, "Test reading a func_odbc function"),
  1292. };
  1293. static int load_module(void)
  1294. {
  1295. int res = 0;
  1296. struct ast_config *cfg;
  1297. char *catg;
  1298. struct ast_flags config_flags = { 0 };
  1299. res |= ast_custom_function_register(&fetch_function);
  1300. res |= ast_register_application_xml(app_odbcfinish, exec_odbcfinish);
  1301. AST_RWLIST_WRLOCK(&queries);
  1302. cfg = ast_config_load(config, config_flags);
  1303. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  1304. ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
  1305. AST_RWLIST_UNLOCK(&queries);
  1306. return AST_MODULE_LOAD_DECLINE;
  1307. }
  1308. for (catg = ast_category_browse(cfg, NULL);
  1309. catg;
  1310. catg = ast_category_browse(cfg, catg)) {
  1311. struct acf_odbc_query *query = NULL;
  1312. int err;
  1313. if ((err = init_acf_query(cfg, catg, &query))) {
  1314. if (err == ENOMEM)
  1315. ast_log(LOG_ERROR, "Out of memory\n");
  1316. else if (err == EINVAL)
  1317. ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
  1318. else
  1319. ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
  1320. } else {
  1321. AST_RWLIST_INSERT_HEAD(&queries, query, list);
  1322. ast_custom_function_register(query->acf);
  1323. }
  1324. }
  1325. ast_config_destroy(cfg);
  1326. res |= ast_custom_function_register(&escape_function);
  1327. ast_cli_register_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
  1328. AST_RWLIST_UNLOCK(&queries);
  1329. return res;
  1330. }
  1331. static int unload_module(void)
  1332. {
  1333. struct acf_odbc_query *query;
  1334. int res = 0;
  1335. AST_RWLIST_WRLOCK(&queries);
  1336. while (!AST_RWLIST_EMPTY(&queries)) {
  1337. query = AST_RWLIST_REMOVE_HEAD(&queries, list);
  1338. ast_custom_function_unregister(query->acf);
  1339. free_acf_query(query);
  1340. }
  1341. res |= ast_custom_function_unregister(&escape_function);
  1342. res |= ast_custom_function_unregister(&fetch_function);
  1343. res |= ast_unregister_application(app_odbcfinish);
  1344. ast_cli_unregister_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
  1345. /* Allow any threads waiting for this lock to pass (avoids a race) */
  1346. AST_RWLIST_UNLOCK(&queries);
  1347. usleep(1);
  1348. AST_RWLIST_WRLOCK(&queries);
  1349. AST_RWLIST_UNLOCK(&queries);
  1350. return res;
  1351. }
  1352. static int reload(void)
  1353. {
  1354. int res = 0;
  1355. struct ast_config *cfg;
  1356. struct acf_odbc_query *oldquery;
  1357. char *catg;
  1358. struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
  1359. cfg = ast_config_load(config, config_flags);
  1360. if (cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
  1361. return 0;
  1362. AST_RWLIST_WRLOCK(&queries);
  1363. while (!AST_RWLIST_EMPTY(&queries)) {
  1364. oldquery = AST_RWLIST_REMOVE_HEAD(&queries, list);
  1365. ast_custom_function_unregister(oldquery->acf);
  1366. free_acf_query(oldquery);
  1367. }
  1368. if (!cfg) {
  1369. ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
  1370. goto reload_out;
  1371. }
  1372. for (catg = ast_category_browse(cfg, NULL);
  1373. catg;
  1374. catg = ast_category_browse(cfg, catg)) {
  1375. struct acf_odbc_query *query = NULL;
  1376. if (init_acf_query(cfg, catg, &query)) {
  1377. ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
  1378. } else {
  1379. AST_RWLIST_INSERT_HEAD(&queries, query, list);
  1380. ast_custom_function_register(query->acf);
  1381. }
  1382. }
  1383. ast_config_destroy(cfg);
  1384. reload_out:
  1385. AST_RWLIST_UNLOCK(&queries);
  1386. return res;
  1387. }
  1388. /* XXX need to revise usecount - set if query_lock is set */
  1389. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
  1390. .support_level = AST_MODULE_SUPPORT_CORE,
  1391. .load = load_module,
  1392. .unload = unload_module,
  1393. .reload = reload,
  1394. );