func_odbc.c 43 KB

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