func_odbc.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950
  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. <depend>generic_odbc</depend>
  31. <support_level>core</support_level>
  32. ***/
  33. #include "asterisk.h"
  34. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  35. #include "asterisk/module.h"
  36. #include "asterisk/file.h"
  37. #include "asterisk/channel.h"
  38. #include "asterisk/pbx.h"
  39. #include "asterisk/config.h"
  40. #include "asterisk/res_odbc.h"
  41. #include "asterisk/res_odbc_transaction.h"
  42. #include "asterisk/app.h"
  43. #include "asterisk/cli.h"
  44. #include "asterisk/strings.h"
  45. /*** DOCUMENTATION
  46. <function name="ODBC_FETCH" language="en_US">
  47. <synopsis>
  48. Fetch a row from a multirow query.
  49. </synopsis>
  50. <syntax>
  51. <parameter name="result-id" required="true" />
  52. </syntax>
  53. <description>
  54. <para>For queries which are marked as mode=multirow, the original
  55. query returns a <replaceable>result-id</replaceable> from which results
  56. may be fetched. This function implements the actual fetch of the results.</para>
  57. <para>This also sets <variable>ODBC_FETCH_STATUS</variable>.</para>
  58. <variablelist>
  59. <variable name="ODBC_FETCH_STATUS">
  60. <value name="SUCESS">
  61. If rows are available.
  62. </value>
  63. <value name="FAILURE">
  64. If no rows are available.
  65. </value>
  66. </variable>
  67. </variablelist>
  68. </description>
  69. </function>
  70. <application name="ODBCFinish" language="en_US">
  71. <synopsis>
  72. Clear the resultset of a sucessful multirow query.
  73. </synopsis>
  74. <syntax>
  75. <parameter name="result-id" required="true" />
  76. </syntax>
  77. <description>
  78. <para>For queries which are marked as mode=multirow, this will clear
  79. any remaining rows of the specified resultset.</para>
  80. </description>
  81. </application>
  82. <function name="SQL_ESC" language="en_US">
  83. <synopsis>
  84. Escapes single ticks for use in SQL statements.
  85. </synopsis>
  86. <syntax>
  87. <parameter name="string" required="true" />
  88. </syntax>
  89. <description>
  90. <para>Used in SQL templates to escape data which may contain single ticks
  91. <literal>'</literal> which are otherwise used to delimit data.</para>
  92. <para>Example: SELECT foo FROM bar WHERE baz='${SQL_ESC(${ARG1})}'</para>
  93. </description>
  94. </function>
  95. ***/
  96. static char *config = "func_odbc.conf";
  97. #define DEFAULT_SINGLE_DB_CONNECTION 1
  98. static int single_db_connection;
  99. AST_RWLOCK_DEFINE_STATIC(single_db_connection_lock);
  100. enum odbc_option_flags {
  101. OPT_ESCAPECOMMAS = (1 << 0),
  102. OPT_MULTIROW = (1 << 1),
  103. };
  104. struct acf_odbc_query {
  105. AST_RWLIST_ENTRY(acf_odbc_query) list;
  106. char readhandle[5][30];
  107. char writehandle[5][30];
  108. char *sql_read;
  109. char *sql_write;
  110. char *sql_insert;
  111. unsigned int flags;
  112. int rowlimit;
  113. struct ast_custom_function *acf;
  114. };
  115. static void odbc_datastore_free(void *data);
  116. static const struct ast_datastore_info odbc_info = {
  117. .type = "FUNC_ODBC",
  118. .destroy = odbc_datastore_free,
  119. };
  120. /* For storing each result row */
  121. struct odbc_datastore_row {
  122. AST_LIST_ENTRY(odbc_datastore_row) list;
  123. char data[0];
  124. };
  125. /* For storing each result set */
  126. struct odbc_datastore {
  127. AST_LIST_HEAD(, odbc_datastore_row);
  128. char names[0];
  129. };
  130. /* \brief Data source name
  131. *
  132. * This holds data that pertains to a DSN
  133. */
  134. struct dsn {
  135. /*! A connection to the database */
  136. struct odbc_obj *connection;
  137. /*! The name of the DSN as defined in res_odbc.conf */
  138. char name[0];
  139. };
  140. #define DSN_BUCKETS 37
  141. struct ao2_container *dsns;
  142. static int dsn_hash(const void *obj, const int flags)
  143. {
  144. const struct dsn *object;
  145. const char *key;
  146. switch (flags & OBJ_SEARCH_MASK) {
  147. case OBJ_SEARCH_KEY:
  148. key = obj;
  149. break;
  150. case OBJ_SEARCH_OBJECT:
  151. object = obj;
  152. key = object->name;
  153. break;
  154. default:
  155. ast_assert(0);
  156. return 0;
  157. }
  158. return ast_str_hash(key);
  159. }
  160. static int dsn_cmp(void *obj, void *arg, int flags)
  161. {
  162. const struct dsn *object_left = obj;
  163. const struct dsn *object_right = arg;
  164. const char *right_key = arg;
  165. int cmp;
  166. switch (flags & OBJ_SEARCH_MASK) {
  167. case OBJ_SEARCH_OBJECT:
  168. right_key = object_right->name;
  169. /* Fall through */
  170. case OBJ_SEARCH_KEY:
  171. cmp = strcmp(object_left->name, right_key);
  172. break;
  173. case OBJ_SEARCH_PARTIAL_KEY:
  174. cmp = strncmp(object_left->name, right_key, strlen(right_key));
  175. break;
  176. default:
  177. cmp = 0;
  178. break;
  179. }
  180. if (cmp) {
  181. return 0;
  182. }
  183. return CMP_MATCH;
  184. }
  185. static void dsn_destructor(void *obj)
  186. {
  187. struct dsn *dsn = obj;
  188. if (dsn->connection) {
  189. ast_odbc_release_obj(dsn->connection);
  190. }
  191. }
  192. /*!
  193. * \brief Create a DSN and connect to the database
  194. *
  195. * \param name The name of the DSN as found in res_odbc.conf
  196. * \retval NULL Fail
  197. * \retval non-NULL The newly-created structure
  198. */
  199. static struct dsn *create_dsn(const char *name)
  200. {
  201. struct dsn *dsn;
  202. if (!dsns) {
  203. return NULL;
  204. }
  205. dsn = ao2_alloc(sizeof(*dsn) + strlen(name) + 1, dsn_destructor);
  206. if (!dsn) {
  207. return NULL;
  208. }
  209. /* Safe */
  210. strcpy(dsn->name, name);
  211. dsn->connection = ast_odbc_request_obj(name, 0);
  212. if (!dsn->connection) {
  213. ao2_ref(dsn, -1);
  214. return NULL;
  215. }
  216. if (!ao2_link_flags(dsns, dsn, OBJ_NOLOCK)) {
  217. ao2_ref(dsn, -1);
  218. return NULL;
  219. }
  220. return dsn;
  221. }
  222. static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data);
  223. /*!
  224. * \brief Determine if the connection has died.
  225. *
  226. * \param connection The connection to check
  227. * \retval 1 Yep, it's dead
  228. * \retval 0 It's alive and well
  229. */
  230. static int connection_dead(struct odbc_obj *connection)
  231. {
  232. SQLINTEGER dead;
  233. SQLRETURN res;
  234. SQLHSTMT stmt;
  235. if (!connection) {
  236. return 1;
  237. }
  238. res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
  239. if (SQL_SUCCEEDED(res)) {
  240. return dead == SQL_CD_TRUE ? 1 : 0;
  241. }
  242. /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a direct
  243. * execute of a probing statement and see if that succeeds instead
  244. */
  245. stmt = ast_odbc_direct_execute(connection, silent_execute, "SELECT 1");
  246. if (!stmt) {
  247. return 1;
  248. }
  249. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  250. return 0;
  251. }
  252. /*!
  253. * \brief Retrieve a DSN, or create it if it does not exist.
  254. *
  255. * The created DSN is returned locked. This should be inconsequential
  256. * to callers in most cases.
  257. *
  258. * When finished with the returned structure, the caller must call
  259. * \ref release_dsn
  260. *
  261. * \param name Name of the DSN as found in res_odbc.conf
  262. * \retval NULL Unable to retrieve or create the DSN
  263. * \retval non-NULL The retrieved/created locked DSN
  264. */
  265. static struct dsn *get_dsn(const char *name)
  266. {
  267. struct dsn *dsn;
  268. if (!dsns) {
  269. return NULL;
  270. }
  271. ao2_lock(dsns);
  272. dsn = ao2_find(dsns, name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
  273. if (!dsn) {
  274. dsn = create_dsn(name);
  275. }
  276. ao2_unlock(dsns);
  277. if (!dsn) {
  278. return NULL;
  279. }
  280. ao2_lock(dsn);
  281. if (!dsn->connection) {
  282. dsn->connection = ast_odbc_request_obj(name, 0);
  283. if (!dsn->connection) {
  284. ao2_unlock(dsn);
  285. ao2_ref(dsn, -1);
  286. return NULL;
  287. }
  288. return dsn;
  289. }
  290. if (connection_dead(dsn->connection)) {
  291. ast_odbc_release_obj(dsn->connection);
  292. dsn->connection = ast_odbc_request_obj(name, 0);
  293. if (!dsn->connection) {
  294. ao2_unlock(dsn);
  295. ao2_ref(dsn, -1);
  296. return NULL;
  297. }
  298. }
  299. return dsn;
  300. }
  301. /*!
  302. * \brief Get a DB handle via a DSN or directly
  303. *
  304. * If single db connection then get the DB handle via DSN
  305. * else by requesting a connection directly
  306. *
  307. * \param dsn_name Name of the DSN as found in res_odbc.conf
  308. * \param dsn The pointer to the DSN
  309. * \retval NULL Unable to retrieve the DB handle
  310. * \retval non-NULL The retrieved DB handle
  311. */
  312. static struct odbc_obj *get_odbc_obj(const char *dsn_name, struct dsn **dsn)
  313. {
  314. struct odbc_obj *obj = NULL;
  315. ast_rwlock_rdlock(&single_db_connection_lock);
  316. if (single_db_connection) {
  317. if (dsn) {
  318. *dsn = get_dsn(dsn_name);
  319. if (*dsn) {
  320. obj = (*dsn)->connection;
  321. }
  322. }
  323. } else {
  324. obj = ast_odbc_request_obj(dsn_name, 0);
  325. }
  326. ast_rwlock_unlock(&single_db_connection_lock);
  327. return obj;
  328. }
  329. /*!
  330. * \brief Release an ODBC obj or a DSN
  331. *
  332. * If single db connection then unlock and unreference the DSN
  333. * else release the ODBC obj
  334. *
  335. * \param obj The pointer to the ODBC obj to release
  336. * \param dsn The pointer to the dsn to unlock and unreference
  337. */
  338. static inline void release_obj_or_dsn(struct odbc_obj **obj, struct dsn **dsn)
  339. {
  340. if (dsn && *dsn) {
  341. /* If multiple connections are not enabled then the guarantee
  342. * of a single connection already exists and holding on to the
  343. * connection would prevent any other user from acquiring it
  344. * indefinitely.
  345. */
  346. if (ast_odbc_get_max_connections((*dsn)->name) < 2) {
  347. ast_odbc_release_obj((*dsn)->connection);
  348. (*dsn)->connection = NULL;
  349. }
  350. ao2_unlock(*dsn);
  351. ao2_ref(*dsn, -1);
  352. *dsn = NULL;
  353. /* Some callers may provide both an obj and dsn. To ensure that
  354. * the connection is not released twice we set it to NULL here if
  355. * present.
  356. */
  357. if (obj) {
  358. *obj = NULL;
  359. }
  360. } else if (obj && *obj) {
  361. ast_odbc_release_obj(*obj);
  362. *obj = NULL;
  363. }
  364. }
  365. static AST_RWLIST_HEAD_STATIC(queries, acf_odbc_query);
  366. static int resultcount = 0;
  367. AST_THREADSTORAGE(sql_buf);
  368. AST_THREADSTORAGE(sql2_buf);
  369. AST_THREADSTORAGE(coldata_buf);
  370. AST_THREADSTORAGE(colnames_buf);
  371. static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len);
  372. static void odbc_datastore_free(void *data)
  373. {
  374. struct odbc_datastore *result = data;
  375. struct odbc_datastore_row *row;
  376. if (!result) {
  377. return;
  378. }
  379. AST_LIST_LOCK(result);
  380. while ((row = AST_LIST_REMOVE_HEAD(result, list))) {
  381. ast_free(row);
  382. }
  383. AST_LIST_UNLOCK(result);
  384. AST_LIST_HEAD_DESTROY(result);
  385. ast_free(result);
  386. }
  387. /*!
  388. * \brief Common execution function for SQL queries.
  389. *
  390. * \param obj DB connection
  391. * \param data The query to execute
  392. * \param silent If true, do not print warnings on failure
  393. * \retval NULL Failed to execute query
  394. * \retval non-NULL The executed statement
  395. */
  396. static SQLHSTMT execute(struct odbc_obj *obj, void *data, int silent)
  397. {
  398. int res;
  399. char *sql = data;
  400. SQLHSTMT stmt;
  401. res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
  402. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  403. ast_log(LOG_WARNING, "SQL Alloc Handle failed (%d)!\n", res);
  404. return NULL;
  405. }
  406. res = SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
  407. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
  408. if (res == SQL_ERROR && !silent) {
  409. int i;
  410. SQLINTEGER nativeerror=0, numfields=0;
  411. SQLSMALLINT diagbytes=0;
  412. unsigned char state[10], diagnostic[256];
  413. SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
  414. for (i = 0; i < numfields; i++) {
  415. SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
  416. ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
  417. if (i > 10) {
  418. ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
  419. break;
  420. }
  421. }
  422. }
  423. if (!silent) {
  424. ast_log(LOG_WARNING, "SQL Exec Direct failed (%d)![%s]\n", res, sql);
  425. }
  426. SQLCloseCursor(stmt);
  427. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  428. return NULL;
  429. }
  430. return stmt;
  431. }
  432. static SQLHSTMT generic_execute(struct odbc_obj *obj, void *data)
  433. {
  434. return execute(obj, data, 0);
  435. }
  436. static SQLHSTMT silent_execute(struct odbc_obj *obj, void *data)
  437. {
  438. return execute(obj, data, 1);
  439. }
  440. /*
  441. * Master control routine
  442. */
  443. static int acf_odbc_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
  444. {
  445. struct odbc_obj *obj = NULL;
  446. struct acf_odbc_query *query;
  447. char *t, varname[15];
  448. int i, dsn_num, bogus_chan = 0;
  449. int transactional = 0;
  450. AST_DECLARE_APP_ARGS(values,
  451. AST_APP_ARG(field)[100];
  452. );
  453. AST_DECLARE_APP_ARGS(args,
  454. AST_APP_ARG(field)[100];
  455. );
  456. SQLHSTMT stmt = NULL;
  457. SQLLEN rows=0;
  458. struct ast_str *buf = ast_str_thread_get(&sql_buf, 16);
  459. struct ast_str *insertbuf = ast_str_thread_get(&sql2_buf, 16);
  460. const char *status = "FAILURE";
  461. struct dsn *dsn = NULL;
  462. if (!buf || !insertbuf) {
  463. return -1;
  464. }
  465. AST_RWLIST_RDLOCK(&queries);
  466. AST_RWLIST_TRAVERSE(&queries, query, list) {
  467. if (!strcmp(query->acf->name, cmd)) {
  468. break;
  469. }
  470. }
  471. if (!query) {
  472. ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
  473. AST_RWLIST_UNLOCK(&queries);
  474. if (chan) {
  475. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  476. }
  477. return -1;
  478. }
  479. if (!chan) {
  480. if (!(chan = ast_dummy_channel_alloc())) {
  481. AST_RWLIST_UNLOCK(&queries);
  482. return -1;
  483. }
  484. bogus_chan = 1;
  485. }
  486. if (!bogus_chan) {
  487. ast_autoservice_start(chan);
  488. }
  489. ast_str_make_space(&buf, strlen(query->sql_write) * 2 + 300);
  490. /* We only get here if sql_write is set. sql_insert is optional however. */
  491. if (query->sql_insert) {
  492. ast_str_make_space(&insertbuf, strlen(query->sql_insert) * 2 + 300);
  493. }
  494. /* Parse our arguments */
  495. t = value ? ast_strdupa(value) : "";
  496. if (!s || !t) {
  497. ast_log(LOG_ERROR, "Out of memory\n");
  498. AST_RWLIST_UNLOCK(&queries);
  499. if (!bogus_chan) {
  500. ast_autoservice_stop(chan);
  501. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  502. } else {
  503. ast_channel_unref(chan);
  504. }
  505. return -1;
  506. }
  507. AST_STANDARD_APP_ARGS(args, s);
  508. for (i = 0; i < args.argc; i++) {
  509. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  510. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  511. }
  512. /* Parse values, just like arguments */
  513. AST_STANDARD_APP_ARGS(values, t);
  514. for (i = 0; i < values.argc; i++) {
  515. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  516. pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
  517. }
  518. /* Additionally set the value as a whole (but push an empty string if value is NULL) */
  519. pbx_builtin_pushvar_helper(chan, "VALUE", value ? value : "");
  520. ast_str_substitute_variables(&buf, 0, chan, query->sql_write);
  521. if (query->sql_insert) {
  522. ast_str_substitute_variables(&insertbuf, 0, chan, query->sql_insert);
  523. }
  524. if (bogus_chan) {
  525. chan = ast_channel_unref(chan);
  526. } else {
  527. /* Restore prior values */
  528. for (i = 0; i < args.argc; i++) {
  529. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  530. pbx_builtin_setvar_helper(chan, varname, NULL);
  531. }
  532. for (i = 0; i < values.argc; i++) {
  533. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  534. pbx_builtin_setvar_helper(chan, varname, NULL);
  535. }
  536. pbx_builtin_setvar_helper(chan, "VALUE", NULL);
  537. }
  538. /*!\note
  539. * Okay, this part is confusing. Transactions belong to a single database
  540. * handle. Therefore, when working with transactions, we CANNOT failover
  541. * to multiple DSNs. We MUST have a single handle all the way through the
  542. * transaction, or else we CANNOT enforce atomicity.
  543. */
  544. for (dsn_num = 0; dsn_num < 5; dsn_num++) {
  545. if (!ast_strlen_zero(query->writehandle[dsn_num])) {
  546. if (transactional) {
  547. /* This can only happen second time through or greater. */
  548. ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
  549. }
  550. if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
  551. transactional = 1;
  552. } else {
  553. obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
  554. transactional = 0;
  555. }
  556. if (obj && (stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(buf)))) {
  557. break;
  558. }
  559. if (!transactional) {
  560. release_obj_or_dsn (&obj, &dsn);
  561. }
  562. }
  563. }
  564. if (stmt) {
  565. SQLRowCount(stmt, &rows);
  566. SQLCloseCursor(stmt);
  567. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  568. if (rows != 0) {
  569. status = "SUCCESS";
  570. } else if (query->sql_insert) {
  571. if (!transactional) {
  572. release_obj_or_dsn (&obj, &dsn);
  573. }
  574. for (transactional = 0, dsn_num = 0; dsn_num < 5; dsn_num++) {
  575. if (!ast_strlen_zero(query->writehandle[dsn_num])) {
  576. if (transactional) {
  577. /* This can only happen second time through or greater. */
  578. ast_log(LOG_WARNING, "Transactions do not work well with multiple DSNs for 'writehandle'\n");
  579. } else {
  580. release_obj_or_dsn (&obj, &dsn);
  581. }
  582. if ((obj = ast_odbc_retrieve_transaction_obj(chan, query->writehandle[dsn_num]))) {
  583. transactional = 1;
  584. } else {
  585. obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
  586. transactional = 0;
  587. }
  588. if (obj) {
  589. stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(insertbuf));
  590. }
  591. }
  592. if (stmt) {
  593. status = "FAILOVER";
  594. SQLRowCount(stmt, &rows);
  595. SQLCloseCursor(stmt);
  596. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  597. break;
  598. }
  599. }
  600. }
  601. }
  602. AST_RWLIST_UNLOCK(&queries);
  603. /* Output the affected rows, for all cases. In the event of failure, we
  604. * flag this as -1 rows. Note that this is different from 0 affected rows
  605. * which would be the case if we succeeded in our query, but the values did
  606. * not change. */
  607. if (!bogus_chan) {
  608. snprintf(varname, sizeof(varname), "%d", (int)rows);
  609. pbx_builtin_setvar_helper(chan, "ODBCROWS", varname);
  610. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  611. }
  612. if (!transactional) {
  613. release_obj_or_dsn (&obj, &dsn);
  614. }
  615. if (!bogus_chan) {
  616. ast_autoservice_stop(chan);
  617. }
  618. return 0;
  619. }
  620. static int acf_odbc_read(struct ast_channel *chan, const char *cmd, char *s, char *buf, size_t len)
  621. {
  622. struct odbc_obj *obj = NULL;
  623. struct acf_odbc_query *query;
  624. char varname[15], rowcount[12] = "-1";
  625. struct ast_str *colnames = ast_str_thread_get(&colnames_buf, 16);
  626. int res, x, y, buflen = 0, escapecommas, rowlimit = 1, multirow = 0, dsn_num, bogus_chan = 0;
  627. AST_DECLARE_APP_ARGS(args,
  628. AST_APP_ARG(field)[100];
  629. );
  630. SQLHSTMT stmt = NULL;
  631. SQLSMALLINT colcount=0;
  632. SQLLEN indicator;
  633. SQLSMALLINT collength;
  634. struct odbc_datastore *resultset = NULL;
  635. struct odbc_datastore_row *row = NULL;
  636. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  637. const char *status = "FAILURE";
  638. struct dsn *dsn = NULL;
  639. if (!sql || !colnames) {
  640. if (chan) {
  641. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  642. }
  643. return -1;
  644. }
  645. ast_str_reset(colnames);
  646. AST_RWLIST_RDLOCK(&queries);
  647. AST_RWLIST_TRAVERSE(&queries, query, list) {
  648. if (!strcmp(query->acf->name, cmd)) {
  649. break;
  650. }
  651. }
  652. if (!query) {
  653. ast_log(LOG_ERROR, "No such function '%s'\n", cmd);
  654. AST_RWLIST_UNLOCK(&queries);
  655. if (chan) {
  656. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  657. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  658. }
  659. return -1;
  660. }
  661. if (!chan) {
  662. if (!(chan = ast_dummy_channel_alloc())) {
  663. AST_RWLIST_UNLOCK(&queries);
  664. return -1;
  665. }
  666. bogus_chan = 1;
  667. }
  668. if (!bogus_chan) {
  669. ast_autoservice_start(chan);
  670. }
  671. AST_STANDARD_APP_ARGS(args, s);
  672. for (x = 0; x < args.argc; x++) {
  673. snprintf(varname, sizeof(varname), "ARG%d", x + 1);
  674. pbx_builtin_pushvar_helper(chan, varname, args.field[x]);
  675. }
  676. ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
  677. if (bogus_chan) {
  678. chan = ast_channel_unref(chan);
  679. } else {
  680. /* Restore prior values */
  681. for (x = 0; x < args.argc; x++) {
  682. snprintf(varname, sizeof(varname), "ARG%d", x + 1);
  683. pbx_builtin_setvar_helper(chan, varname, NULL);
  684. }
  685. }
  686. /* Save these flags, so we can release the lock */
  687. escapecommas = ast_test_flag(query, OPT_ESCAPECOMMAS);
  688. if (!bogus_chan && ast_test_flag(query, OPT_MULTIROW)) {
  689. if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
  690. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  691. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  692. AST_RWLIST_UNLOCK(&queries);
  693. ast_autoservice_stop(chan);
  694. return -1;
  695. }
  696. AST_LIST_HEAD_INIT(resultset);
  697. if (query->rowlimit) {
  698. rowlimit = query->rowlimit;
  699. } else {
  700. rowlimit = INT_MAX;
  701. }
  702. multirow = 1;
  703. } else if (!bogus_chan) {
  704. if (query->rowlimit > 1) {
  705. rowlimit = query->rowlimit;
  706. if (!(resultset = ast_calloc(1, sizeof(*resultset)))) {
  707. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  708. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  709. AST_RWLIST_UNLOCK(&queries);
  710. ast_autoservice_stop(chan);
  711. return -1;
  712. }
  713. AST_LIST_HEAD_INIT(resultset);
  714. }
  715. }
  716. AST_RWLIST_UNLOCK(&queries);
  717. for (dsn_num = 0; dsn_num < 5; dsn_num++) {
  718. if (!ast_strlen_zero(query->readhandle[dsn_num])) {
  719. obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
  720. if (!obj) {
  721. continue;
  722. }
  723. stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql));
  724. }
  725. if (stmt) {
  726. break;
  727. }
  728. release_obj_or_dsn (&obj, &dsn);
  729. }
  730. if (!stmt) {
  731. ast_log(LOG_ERROR, "Unable to execute query [%s]\n", ast_str_buffer(sql));
  732. release_obj_or_dsn (&obj, &dsn);
  733. if (!bogus_chan) {
  734. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  735. ast_autoservice_stop(chan);
  736. }
  737. odbc_datastore_free(resultset);
  738. return -1;
  739. }
  740. res = SQLNumResultCols(stmt, &colcount);
  741. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  742. ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
  743. SQLCloseCursor(stmt);
  744. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  745. release_obj_or_dsn (&obj, &dsn);
  746. if (!bogus_chan) {
  747. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  748. ast_autoservice_stop(chan);
  749. }
  750. odbc_datastore_free(resultset);
  751. return -1;
  752. }
  753. if (colcount <= 0) {
  754. ast_verb(4, "Returned %d columns [%s]\n", colcount, ast_str_buffer(sql));
  755. buf[0] = '\0';
  756. SQLCloseCursor(stmt);
  757. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  758. release_obj_or_dsn (&obj, &dsn);
  759. if (!bogus_chan) {
  760. pbx_builtin_setvar_helper(chan, "ODBCROWS", "0");
  761. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "NODATA");
  762. ast_autoservice_stop(chan);
  763. }
  764. odbc_datastore_free(resultset);
  765. return 0;
  766. }
  767. res = SQLFetch(stmt);
  768. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  769. int res1 = -1;
  770. if (res == SQL_NO_DATA) {
  771. ast_verb(4, "Found no rows [%s]\n", ast_str_buffer(sql));
  772. res1 = 0;
  773. buf[0] = '\0';
  774. ast_copy_string(rowcount, "0", sizeof(rowcount));
  775. status = "NODATA";
  776. } else {
  777. ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  778. status = "FETCHERROR";
  779. }
  780. SQLCloseCursor(stmt);
  781. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  782. release_obj_or_dsn (&obj, &dsn);
  783. if (!bogus_chan) {
  784. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  785. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  786. ast_autoservice_stop(chan);
  787. }
  788. odbc_datastore_free(resultset);
  789. return res1;
  790. }
  791. status = "SUCCESS";
  792. for (y = 0; y < rowlimit; y++) {
  793. buf[0] = '\0';
  794. for (x = 0; x < colcount; x++) {
  795. int i;
  796. struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
  797. char *ptrcoldata;
  798. if (!coldata) {
  799. odbc_datastore_free(resultset);
  800. SQLCloseCursor(stmt);
  801. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  802. release_obj_or_dsn (&obj, &dsn);
  803. if (!bogus_chan) {
  804. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  805. ast_autoservice_stop(chan);
  806. }
  807. return -1;
  808. }
  809. if (y == 0) {
  810. char colname[256];
  811. SQLULEN maxcol = 0;
  812. res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
  813. ast_debug(3, "Got collength of %d and maxcol of %d for column '%s' (offset %d)\n", (int)collength, (int)maxcol, colname, x);
  814. if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
  815. snprintf(colname, sizeof(colname), "field%d", x);
  816. }
  817. ast_str_make_space(&coldata, maxcol + 1);
  818. if (ast_str_strlen(colnames)) {
  819. ast_str_append(&colnames, 0, ",");
  820. }
  821. ast_str_append_escapecommas(&colnames, 0, colname, sizeof(colname));
  822. if (resultset) {
  823. void *tmp = ast_realloc(resultset, sizeof(*resultset) + ast_str_strlen(colnames) + 1);
  824. if (!tmp) {
  825. ast_log(LOG_ERROR, "No space for a new resultset?\n");
  826. odbc_datastore_free(resultset);
  827. SQLCloseCursor(stmt);
  828. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  829. release_obj_or_dsn (&obj, &dsn);
  830. if (!bogus_chan) {
  831. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  832. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  833. ast_autoservice_stop(chan);
  834. }
  835. return -1;
  836. }
  837. resultset = tmp;
  838. strcpy((char *)resultset + sizeof(*resultset), ast_str_buffer(colnames));
  839. }
  840. }
  841. buflen = strlen(buf);
  842. res = ast_odbc_ast_str_SQLGetData(&coldata, -1, stmt, x + 1, SQL_CHAR, &indicator);
  843. if (indicator == SQL_NULL_DATA) {
  844. ast_debug(3, "Got NULL data\n");
  845. ast_str_reset(coldata);
  846. res = SQL_SUCCESS;
  847. }
  848. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  849. ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", ast_str_buffer(sql));
  850. y = -1;
  851. buf[0] = '\0';
  852. goto end_acf_read;
  853. }
  854. ast_debug(2, "Got coldata of '%s'\n", ast_str_buffer(coldata));
  855. if (x) {
  856. buf[buflen++] = ',';
  857. }
  858. /* Copy data, encoding '\' and ',' for the argument parser */
  859. ptrcoldata = ast_str_buffer(coldata);
  860. for (i = 0; i < ast_str_strlen(coldata); i++) {
  861. if (escapecommas && (ptrcoldata[i] == '\\' || ptrcoldata[i] == ',')) {
  862. buf[buflen++] = '\\';
  863. }
  864. buf[buflen++] = ptrcoldata[i];
  865. if (buflen >= len - 2) {
  866. break;
  867. }
  868. if (ptrcoldata[i] == '\0') {
  869. break;
  870. }
  871. }
  872. buf[buflen] = '\0';
  873. ast_debug(2, "buf is now set to '%s'\n", buf);
  874. }
  875. ast_debug(2, "buf is now set to '%s'\n", buf);
  876. if (resultset) {
  877. row = ast_calloc(1, sizeof(*row) + buflen + 1);
  878. if (!row) {
  879. ast_log(LOG_ERROR, "Unable to allocate space for more rows in this resultset.\n");
  880. status = "MEMERROR";
  881. goto end_acf_read;
  882. }
  883. strcpy((char *)row + sizeof(*row), buf);
  884. AST_LIST_INSERT_TAIL(resultset, row, list);
  885. /* Get next row */
  886. res = SQLFetch(stmt);
  887. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  888. if (res != SQL_NO_DATA) {
  889. ast_log(LOG_WARNING, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  890. }
  891. /* Number of rows in the resultset */
  892. y++;
  893. break;
  894. }
  895. }
  896. }
  897. end_acf_read:
  898. if (!bogus_chan) {
  899. snprintf(rowcount, sizeof(rowcount), "%d", y);
  900. pbx_builtin_setvar_helper(chan, "ODBCROWS", rowcount);
  901. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", status);
  902. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", ast_str_buffer(colnames));
  903. if (resultset) {
  904. struct ast_datastore *odbc_store;
  905. if (multirow) {
  906. int uid;
  907. uid = ast_atomic_fetchadd_int(&resultcount, +1) + 1;
  908. snprintf(buf, len, "%d", uid);
  909. } else {
  910. /* Name of the query is name of the resultset */
  911. ast_copy_string(buf, cmd, len);
  912. /* If there's one with the same name already, free it */
  913. ast_channel_lock(chan);
  914. if ((odbc_store = ast_channel_datastore_find(chan, &odbc_info, buf))) {
  915. ast_channel_datastore_remove(chan, odbc_store);
  916. ast_datastore_free(odbc_store);
  917. }
  918. ast_channel_unlock(chan);
  919. }
  920. odbc_store = ast_datastore_alloc(&odbc_info, buf);
  921. if (!odbc_store) {
  922. ast_log(LOG_ERROR, "Rows retrieved, but unable to store it in the channel. Results fail.\n");
  923. odbc_datastore_free(resultset);
  924. SQLCloseCursor(stmt);
  925. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  926. release_obj_or_dsn (&obj, &dsn);
  927. pbx_builtin_setvar_helper(chan, "ODBCSTATUS", "MEMERROR");
  928. ast_autoservice_stop(chan);
  929. return -1;
  930. }
  931. odbc_store->data = resultset;
  932. ast_channel_lock(chan);
  933. ast_channel_datastore_add(chan, odbc_store);
  934. ast_channel_unlock(chan);
  935. }
  936. }
  937. SQLCloseCursor(stmt);
  938. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  939. release_obj_or_dsn (&obj, &dsn);
  940. if (resultset && !multirow) {
  941. /* Fetch the first resultset */
  942. if (!acf_fetch(chan, "", buf, buf, len)) {
  943. buf[0] = '\0';
  944. }
  945. }
  946. if (!bogus_chan) {
  947. ast_autoservice_stop(chan);
  948. }
  949. return 0;
  950. }
  951. static int acf_escape(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  952. {
  953. char *out = buf;
  954. for (; *data && out - buf < len; data++) {
  955. if (*data == '\'') {
  956. *out = '\'';
  957. out++;
  958. }
  959. *out++ = *data;
  960. }
  961. *out = '\0';
  962. return 0;
  963. }
  964. static struct ast_custom_function escape_function = {
  965. .name = "SQL_ESC",
  966. .read = acf_escape,
  967. .write = NULL,
  968. };
  969. static int acf_fetch(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  970. {
  971. struct ast_datastore *store;
  972. struct odbc_datastore *resultset;
  973. struct odbc_datastore_row *row;
  974. if (!chan) {
  975. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  976. return -1;
  977. }
  978. ast_channel_lock(chan);
  979. store = ast_channel_datastore_find(chan, &odbc_info, data);
  980. if (!store) {
  981. ast_channel_unlock(chan);
  982. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
  983. return -1;
  984. }
  985. resultset = store->data;
  986. AST_LIST_LOCK(resultset);
  987. row = AST_LIST_REMOVE_HEAD(resultset, list);
  988. AST_LIST_UNLOCK(resultset);
  989. if (!row) {
  990. /* Cleanup datastore */
  991. ast_channel_datastore_remove(chan, store);
  992. ast_datastore_free(store);
  993. ast_channel_unlock(chan);
  994. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "FAILURE");
  995. return -1;
  996. }
  997. pbx_builtin_setvar_helper(chan, "~ODBCFIELDS~", resultset->names);
  998. ast_channel_unlock(chan);
  999. ast_copy_string(buf, row->data, len);
  1000. ast_free(row);
  1001. pbx_builtin_setvar_helper(chan, "ODBC_FETCH_STATUS", "SUCCESS");
  1002. return 0;
  1003. }
  1004. static struct ast_custom_function fetch_function = {
  1005. .name = "ODBC_FETCH",
  1006. .read = acf_fetch,
  1007. .write = NULL,
  1008. };
  1009. static char *app_odbcfinish = "ODBCFinish";
  1010. static int exec_odbcfinish(struct ast_channel *chan, const char *data)
  1011. {
  1012. struct ast_datastore *store;
  1013. ast_channel_lock(chan);
  1014. store = ast_channel_datastore_find(chan, &odbc_info, data);
  1015. if (store) {
  1016. ast_channel_datastore_remove(chan, store);
  1017. ast_datastore_free(store);
  1018. }
  1019. ast_channel_unlock(chan);
  1020. return 0;
  1021. }
  1022. static int free_acf_query(struct acf_odbc_query *query)
  1023. {
  1024. if (query) {
  1025. if (query->acf) {
  1026. if (query->acf->name)
  1027. ast_free((char *)query->acf->name);
  1028. ast_string_field_free_memory(query->acf);
  1029. ast_free(query->acf);
  1030. }
  1031. ast_free(query->sql_read);
  1032. ast_free(query->sql_write);
  1033. ast_free(query->sql_insert);
  1034. ast_free(query);
  1035. }
  1036. return 0;
  1037. }
  1038. static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_query **query)
  1039. {
  1040. const char *tmp;
  1041. const char *tmp2;
  1042. int i;
  1043. if (!cfg || !catg) {
  1044. return EINVAL;
  1045. }
  1046. if (!(*query = ast_calloc(1, sizeof(**query)))) {
  1047. return ENOMEM;
  1048. }
  1049. if (((tmp = ast_variable_retrieve(cfg, catg, "writehandle"))) || ((tmp = ast_variable_retrieve(cfg, catg, "dsn")))) {
  1050. char *tmp2 = ast_strdupa(tmp);
  1051. AST_DECLARE_APP_ARGS(writeconf,
  1052. AST_APP_ARG(dsn)[5];
  1053. );
  1054. AST_STANDARD_APP_ARGS(writeconf, tmp2);
  1055. for (i = 0; i < 5; i++) {
  1056. if (!ast_strlen_zero(writeconf.dsn[i]))
  1057. ast_copy_string((*query)->writehandle[i], writeconf.dsn[i], sizeof((*query)->writehandle[i]));
  1058. }
  1059. }
  1060. if ((tmp = ast_variable_retrieve(cfg, catg, "readhandle"))) {
  1061. char *tmp2 = ast_strdupa(tmp);
  1062. AST_DECLARE_APP_ARGS(readconf,
  1063. AST_APP_ARG(dsn)[5];
  1064. );
  1065. AST_STANDARD_APP_ARGS(readconf, tmp2);
  1066. for (i = 0; i < 5; i++) {
  1067. if (!ast_strlen_zero(readconf.dsn[i]))
  1068. ast_copy_string((*query)->readhandle[i], readconf.dsn[i], sizeof((*query)->readhandle[i]));
  1069. }
  1070. } else {
  1071. /* If no separate readhandle, then use the writehandle for reading */
  1072. for (i = 0; i < 5; i++) {
  1073. if (!ast_strlen_zero((*query)->writehandle[i]))
  1074. ast_copy_string((*query)->readhandle[i], (*query)->writehandle[i], sizeof((*query)->readhandle[i]));
  1075. }
  1076. }
  1077. if ((tmp = ast_variable_retrieve(cfg, catg, "readsql")) ||
  1078. (tmp2 = ast_variable_retrieve(cfg, catg, "read"))) {
  1079. if (!tmp) {
  1080. ast_log(LOG_WARNING, "Parameter 'read' is deprecated for category %s. Please use 'readsql' instead.\n", catg);
  1081. tmp = tmp2;
  1082. }
  1083. if (*tmp != '\0') { /* non-empty string */
  1084. if (!((*query)->sql_read = ast_strdup(tmp))) {
  1085. free_acf_query(*query);
  1086. *query = NULL;
  1087. return ENOMEM;
  1088. }
  1089. }
  1090. }
  1091. if ((*query)->sql_read && ast_strlen_zero((*query)->readhandle[0])) {
  1092. free_acf_query(*query);
  1093. *query = NULL;
  1094. ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
  1095. return EINVAL;
  1096. }
  1097. if ((tmp = ast_variable_retrieve(cfg, catg, "writesql")) ||
  1098. (tmp2 = ast_variable_retrieve(cfg, catg, "write"))) {
  1099. if (!tmp) {
  1100. ast_log(LOG_WARNING, "Parameter 'write' is deprecated for category %s. Please use 'writesql' instead.\n", catg);
  1101. tmp = tmp2;
  1102. }
  1103. if (*tmp != '\0') { /* non-empty string */
  1104. if (!((*query)->sql_write = ast_strdup(tmp))) {
  1105. free_acf_query(*query);
  1106. *query = NULL;
  1107. return ENOMEM;
  1108. }
  1109. }
  1110. }
  1111. if ((*query)->sql_write && ast_strlen_zero((*query)->writehandle[0])) {
  1112. free_acf_query(*query);
  1113. *query = NULL;
  1114. ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
  1115. return EINVAL;
  1116. }
  1117. if ((tmp = ast_variable_retrieve(cfg, catg, "insertsql"))) {
  1118. if (*tmp != '\0') { /* non-empty string */
  1119. if (!((*query)->sql_insert = ast_strdup(tmp))) {
  1120. free_acf_query(*query);
  1121. *query = NULL;
  1122. return ENOMEM;
  1123. }
  1124. }
  1125. }
  1126. /* Allow escaping of embedded commas in fields to be turned off */
  1127. ast_set_flag((*query), OPT_ESCAPECOMMAS);
  1128. if ((tmp = ast_variable_retrieve(cfg, catg, "escapecommas"))) {
  1129. if (ast_false(tmp))
  1130. ast_clear_flag((*query), OPT_ESCAPECOMMAS);
  1131. }
  1132. if ((tmp = ast_variable_retrieve(cfg, catg, "mode"))) {
  1133. if (strcasecmp(tmp, "multirow") == 0)
  1134. ast_set_flag((*query), OPT_MULTIROW);
  1135. if ((tmp = ast_variable_retrieve(cfg, catg, "rowlimit")))
  1136. sscanf(tmp, "%30d", &((*query)->rowlimit));
  1137. }
  1138. (*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
  1139. if (!(*query)->acf) {
  1140. free_acf_query(*query);
  1141. *query = NULL;
  1142. return ENOMEM;
  1143. }
  1144. if (ast_string_field_init((*query)->acf, 128)) {
  1145. free_acf_query(*query);
  1146. *query = NULL;
  1147. return ENOMEM;
  1148. }
  1149. if ((tmp = ast_variable_retrieve(cfg, catg, "prefix")) && !ast_strlen_zero(tmp)) {
  1150. if (ast_asprintf((char **)&((*query)->acf->name), "%s_%s", tmp, catg) < 0) {
  1151. (*query)->acf->name = NULL;
  1152. }
  1153. } else {
  1154. if (ast_asprintf((char **)&((*query)->acf->name), "ODBC_%s", catg) < 0) {
  1155. (*query)->acf->name = NULL;
  1156. }
  1157. }
  1158. if (!(*query)->acf->name) {
  1159. free_acf_query(*query);
  1160. *query = NULL;
  1161. return ENOMEM;
  1162. }
  1163. if ((tmp = ast_variable_retrieve(cfg, catg, "syntax")) && !ast_strlen_zero(tmp)) {
  1164. ast_string_field_build((*query)->acf, syntax, "%s(%s)", (*query)->acf->name, tmp);
  1165. } else {
  1166. ast_string_field_build((*query)->acf, syntax, "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
  1167. }
  1168. if (ast_strlen_zero((*query)->acf->syntax)) {
  1169. free_acf_query(*query);
  1170. *query = NULL;
  1171. return ENOMEM;
  1172. }
  1173. if ((tmp = ast_variable_retrieve(cfg, catg, "synopsis")) && !ast_strlen_zero(tmp)) {
  1174. ast_string_field_set((*query)->acf, synopsis, tmp);
  1175. } else {
  1176. ast_string_field_set((*query)->acf, synopsis, "Runs the referenced query with the specified arguments");
  1177. }
  1178. if (ast_strlen_zero((*query)->acf->synopsis)) {
  1179. free_acf_query(*query);
  1180. *query = NULL;
  1181. return ENOMEM;
  1182. }
  1183. if ((*query)->sql_read && (*query)->sql_write) {
  1184. ast_string_field_build((*query)->acf, desc,
  1185. "Runs the following query, as defined in func_odbc.conf, performing\n"
  1186. "substitution of the arguments into the query as specified by ${ARG1},\n"
  1187. "${ARG2}, ... ${ARGn}. When setting the function, the values are provided\n"
  1188. "either in whole as ${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
  1189. "%s"
  1190. "\nRead:\n%s\n\nWrite:\n%s%s%s",
  1191. (*query)->sql_insert ?
  1192. "If the write query affects no rows, the insert query will be\n"
  1193. "performed.\n" : "",
  1194. (*query)->sql_read,
  1195. (*query)->sql_write,
  1196. (*query)->sql_insert ? "\n\nInsert:\n" : "",
  1197. (*query)->sql_insert ? (*query)->sql_insert : "");
  1198. } else if ((*query)->sql_read) {
  1199. ast_string_field_build((*query)->acf, desc,
  1200. "Runs the following query, as defined in func_odbc.conf, performing\n"
  1201. "substitution of the arguments into the query as specified by ${ARG1},\n"
  1202. "${ARG2}, ... ${ARGn}. This function may only be read, not set.\n\nSQL:\n%s",
  1203. (*query)->sql_read);
  1204. } else if ((*query)->sql_write) {
  1205. ast_string_field_build((*query)->acf, desc,
  1206. "Runs the following query, as defined in func_odbc.conf, performing\n"
  1207. "substitution of the arguments into the query as specified by ${ARG1},\n"
  1208. "${ARG2}, ... ${ARGn}. The values are provided either in whole as\n"
  1209. "${VALUE} or parsed as ${VAL1}, ${VAL2}, ... ${VALn}.\n"
  1210. "This function may only be set.\n%s\nSQL:\n%s%s%s",
  1211. (*query)->sql_insert ?
  1212. "If the write query affects no rows, the insert query will be\n"
  1213. "performed.\n" : "",
  1214. (*query)->sql_write,
  1215. (*query)->sql_insert ? "\n\nInsert:\n" : "",
  1216. (*query)->sql_insert ? (*query)->sql_insert : "");
  1217. } else {
  1218. free_acf_query(*query);
  1219. *query = NULL;
  1220. ast_log(LOG_WARNING, "Section '%s' was found, but there was no SQL to execute. Ignoring.\n", catg);
  1221. return EINVAL;
  1222. }
  1223. if (ast_strlen_zero((*query)->acf->desc)) {
  1224. free_acf_query(*query);
  1225. *query = NULL;
  1226. return ENOMEM;
  1227. }
  1228. if ((*query)->sql_read) {
  1229. (*query)->acf->read = acf_odbc_read;
  1230. }
  1231. if ((*query)->sql_write) {
  1232. (*query)->acf->write = acf_odbc_write;
  1233. }
  1234. return 0;
  1235. }
  1236. static char *cli_odbc_read(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1237. {
  1238. AST_DECLARE_APP_ARGS(args,
  1239. AST_APP_ARG(field)[100];
  1240. );
  1241. struct ast_str *sql;
  1242. char *char_args, varname[10];
  1243. struct acf_odbc_query *query;
  1244. struct ast_channel *chan;
  1245. int i;
  1246. switch (cmd) {
  1247. case CLI_INIT:
  1248. e->command = "odbc read";
  1249. e->usage =
  1250. "Usage: odbc read <name> <args> [exec]\n"
  1251. " Evaluates the SQL provided in the ODBC function <name>, and\n"
  1252. " optionally executes the function. This function is intended for\n"
  1253. " testing purposes. Remember to quote arguments containing spaces.\n";
  1254. return NULL;
  1255. case CLI_GENERATE:
  1256. if (a->pos == 2) {
  1257. int wordlen = strlen(a->word), which = 0;
  1258. /* Complete function name */
  1259. AST_RWLIST_RDLOCK(&queries);
  1260. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1261. if (!strncasecmp(query->acf->name, a->word, wordlen)) {
  1262. if (++which > a->n) {
  1263. char *res = ast_strdup(query->acf->name);
  1264. AST_RWLIST_UNLOCK(&queries);
  1265. return res;
  1266. }
  1267. }
  1268. }
  1269. AST_RWLIST_UNLOCK(&queries);
  1270. return NULL;
  1271. } else if (a->pos == 4) {
  1272. static const char * const completions[] = { "exec", NULL };
  1273. return ast_cli_complete(a->word, completions, a->n);
  1274. } else {
  1275. return NULL;
  1276. }
  1277. }
  1278. if (a->argc < 4 || a->argc > 5) {
  1279. return CLI_SHOWUSAGE;
  1280. }
  1281. sql = ast_str_thread_get(&sql_buf, 16);
  1282. if (!sql) {
  1283. return CLI_FAILURE;
  1284. }
  1285. AST_RWLIST_RDLOCK(&queries);
  1286. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1287. if (!strcmp(query->acf->name, a->argv[2])) {
  1288. break;
  1289. }
  1290. }
  1291. if (!query) {
  1292. ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
  1293. AST_RWLIST_UNLOCK(&queries);
  1294. return CLI_SHOWUSAGE;
  1295. }
  1296. if (!query->sql_read) {
  1297. ast_cli(a->fd, "The function %s has no readsql parameter.\n", a->argv[2]);
  1298. AST_RWLIST_UNLOCK(&queries);
  1299. return CLI_SUCCESS;
  1300. }
  1301. ast_str_make_space(&sql, strlen(query->sql_read) * 2 + 300);
  1302. /* Evaluate function */
  1303. char_args = ast_strdupa(a->argv[3]);
  1304. chan = ast_dummy_channel_alloc();
  1305. if (!chan) {
  1306. AST_RWLIST_UNLOCK(&queries);
  1307. return CLI_FAILURE;
  1308. }
  1309. AST_STANDARD_APP_ARGS(args, char_args);
  1310. for (i = 0; i < args.argc; i++) {
  1311. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  1312. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  1313. }
  1314. ast_str_substitute_variables(&sql, 0, chan, query->sql_read);
  1315. chan = ast_channel_unref(chan);
  1316. if (a->argc == 5 && !strcmp(a->argv[4], "exec")) {
  1317. /* Execute the query */
  1318. struct odbc_obj *obj = NULL;
  1319. struct dsn *dsn = NULL;
  1320. int dsn_num, executed = 0;
  1321. SQLHSTMT stmt;
  1322. int rows = 0, res, x;
  1323. SQLSMALLINT colcount = 0, collength;
  1324. SQLLEN indicator;
  1325. struct ast_str *coldata = ast_str_thread_get(&coldata_buf, 16);
  1326. char colname[256];
  1327. SQLULEN maxcol;
  1328. if (!coldata) {
  1329. AST_RWLIST_UNLOCK(&queries);
  1330. return CLI_SUCCESS;
  1331. }
  1332. for (dsn_num = 0; dsn_num < 5; dsn_num++) {
  1333. if (ast_strlen_zero(query->readhandle[dsn_num])) {
  1334. continue;
  1335. }
  1336. obj = get_odbc_obj(query->readhandle[dsn_num], &dsn);
  1337. if (!obj) {
  1338. continue;
  1339. }
  1340. ast_debug(1, "Found handle %s\n", query->readhandle[dsn_num]);
  1341. if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
  1342. release_obj_or_dsn (&obj, &dsn);
  1343. continue;
  1344. }
  1345. executed = 1;
  1346. res = SQLNumResultCols(stmt, &colcount);
  1347. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1348. ast_cli(a->fd, "SQL Column Count error!\n[%s]\n\n", ast_str_buffer(sql));
  1349. SQLCloseCursor(stmt);
  1350. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  1351. release_obj_or_dsn (&obj, &dsn);
  1352. AST_RWLIST_UNLOCK(&queries);
  1353. return CLI_SUCCESS;
  1354. }
  1355. if (colcount <= 0) {
  1356. SQLCloseCursor(stmt);
  1357. SQLFreeHandle (SQL_HANDLE_STMT, stmt);
  1358. release_obj_or_dsn (&obj, &dsn);
  1359. ast_cli(a->fd, "Returned %d columns. Query executed on handle %d:%s [%s]\n", colcount, dsn_num, query->readhandle[dsn_num], ast_str_buffer(sql));
  1360. AST_RWLIST_UNLOCK(&queries);
  1361. return CLI_SUCCESS;
  1362. }
  1363. res = SQLFetch(stmt);
  1364. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1365. SQLCloseCursor(stmt);
  1366. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1367. release_obj_or_dsn (&obj, &dsn);
  1368. if (res == SQL_NO_DATA) {
  1369. ast_cli(a->fd, "Returned %d rows. Query executed on handle %d:%s [%s]\n", rows, dsn_num, query->readhandle[dsn_num], ast_str_buffer(sql));
  1370. break;
  1371. } else {
  1372. ast_cli(a->fd, "Error %d in FETCH [%s]\n", res, ast_str_buffer(sql));
  1373. }
  1374. AST_RWLIST_UNLOCK(&queries);
  1375. return CLI_SUCCESS;
  1376. }
  1377. for (;;) {
  1378. for (x = 0; x < colcount; x++) {
  1379. maxcol = 0;
  1380. res = SQLDescribeCol(stmt, x + 1, (unsigned char *)colname, sizeof(colname), &collength, NULL, &maxcol, NULL, NULL);
  1381. if (((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) || collength == 0) {
  1382. snprintf(colname, sizeof(colname), "field%d", x);
  1383. }
  1384. res = ast_odbc_ast_str_SQLGetData(&coldata, maxcol, stmt, x + 1, SQL_CHAR, &indicator);
  1385. if (indicator == SQL_NULL_DATA) {
  1386. ast_str_set(&coldata, 0, "(nil)");
  1387. res = SQL_SUCCESS;
  1388. }
  1389. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1390. ast_cli(a->fd, "SQL Get Data error %d!\n[%s]\n\n", res, ast_str_buffer(sql));
  1391. SQLCloseCursor(stmt);
  1392. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1393. release_obj_or_dsn (&obj, &dsn);
  1394. AST_RWLIST_UNLOCK(&queries);
  1395. return CLI_SUCCESS;
  1396. }
  1397. ast_cli(a->fd, "%-20.20s %s\n", colname, ast_str_buffer(coldata));
  1398. }
  1399. rows++;
  1400. /* Get next row */
  1401. res = SQLFetch(stmt);
  1402. if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
  1403. break;
  1404. }
  1405. ast_cli(a->fd, "%-20.20s %s\n", "----------", "----------");
  1406. }
  1407. SQLCloseCursor(stmt);
  1408. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1409. release_obj_or_dsn (&obj, &dsn);
  1410. ast_cli(a->fd, "Returned %d row%s. Query executed on handle %d [%s]\n", rows, rows == 1 ? "" : "s", dsn_num, query->readhandle[dsn_num]);
  1411. break;
  1412. }
  1413. release_obj_or_dsn (&obj, &dsn);
  1414. if (!executed) {
  1415. ast_cli(a->fd, "Failed to execute query. [%s]\n", ast_str_buffer(sql));
  1416. }
  1417. } else { /* No execution, just print out the resulting SQL */
  1418. ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
  1419. }
  1420. AST_RWLIST_UNLOCK(&queries);
  1421. return CLI_SUCCESS;
  1422. }
  1423. static char *cli_odbc_write(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1424. {
  1425. AST_DECLARE_APP_ARGS(values,
  1426. AST_APP_ARG(field)[100];
  1427. );
  1428. AST_DECLARE_APP_ARGS(args,
  1429. AST_APP_ARG(field)[100];
  1430. );
  1431. struct ast_str *sql;
  1432. char *char_args, *char_values, varname[10];
  1433. struct acf_odbc_query *query;
  1434. struct ast_channel *chan;
  1435. int i;
  1436. switch (cmd) {
  1437. case CLI_INIT:
  1438. e->command = "odbc write";
  1439. e->usage =
  1440. "Usage: odbc write <name> <args> <value> [exec]\n"
  1441. " Evaluates the SQL provided in the ODBC function <name>, and\n"
  1442. " optionally executes the function. This function is intended for\n"
  1443. " testing purposes. Remember to quote arguments containing spaces.\n";
  1444. return NULL;
  1445. case CLI_GENERATE:
  1446. if (a->pos == 2) {
  1447. int wordlen = strlen(a->word), which = 0;
  1448. /* Complete function name */
  1449. AST_RWLIST_RDLOCK(&queries);
  1450. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1451. if (!strncasecmp(query->acf->name, a->word, wordlen)) {
  1452. if (++which > a->n) {
  1453. char *res = ast_strdup(query->acf->name);
  1454. AST_RWLIST_UNLOCK(&queries);
  1455. return res;
  1456. }
  1457. }
  1458. }
  1459. AST_RWLIST_UNLOCK(&queries);
  1460. return NULL;
  1461. } else if (a->pos == 5) {
  1462. static const char * const completions[] = { "exec", NULL };
  1463. return ast_cli_complete(a->word, completions, a->n);
  1464. } else {
  1465. return NULL;
  1466. }
  1467. }
  1468. if (a->argc < 5 || a->argc > 6) {
  1469. return CLI_SHOWUSAGE;
  1470. }
  1471. sql = ast_str_thread_get(&sql_buf, 16);
  1472. if (!sql) {
  1473. return CLI_FAILURE;
  1474. }
  1475. AST_RWLIST_RDLOCK(&queries);
  1476. AST_RWLIST_TRAVERSE(&queries, query, list) {
  1477. if (!strcmp(query->acf->name, a->argv[2])) {
  1478. break;
  1479. }
  1480. }
  1481. if (!query) {
  1482. ast_cli(a->fd, "No such query '%s'\n", a->argv[2]);
  1483. AST_RWLIST_UNLOCK(&queries);
  1484. return CLI_SHOWUSAGE;
  1485. }
  1486. if (!query->sql_write) {
  1487. ast_cli(a->fd, "The function %s has no writesql parameter.\n", a->argv[2]);
  1488. AST_RWLIST_UNLOCK(&queries);
  1489. return CLI_SUCCESS;
  1490. }
  1491. /* FIXME: The code below duplicates code found in acf_odbc_write but
  1492. * lacks the newer sql_insert additions. */
  1493. ast_str_make_space(&sql, strlen(query->sql_write) * 2 + 300);
  1494. /* Evaluate function */
  1495. char_args = ast_strdupa(a->argv[3]);
  1496. char_values = ast_strdupa(a->argv[4]);
  1497. chan = ast_dummy_channel_alloc();
  1498. if (!chan) {
  1499. AST_RWLIST_UNLOCK(&queries);
  1500. return CLI_FAILURE;
  1501. }
  1502. AST_STANDARD_APP_ARGS(args, char_args);
  1503. for (i = 0; i < args.argc; i++) {
  1504. snprintf(varname, sizeof(varname), "ARG%d", i + 1);
  1505. pbx_builtin_pushvar_helper(chan, varname, args.field[i]);
  1506. }
  1507. /* Parse values, just like arguments */
  1508. AST_STANDARD_APP_ARGS(values, char_values);
  1509. for (i = 0; i < values.argc; i++) {
  1510. snprintf(varname, sizeof(varname), "VAL%d", i + 1);
  1511. pbx_builtin_pushvar_helper(chan, varname, values.field[i]);
  1512. }
  1513. /* Additionally set the value as a whole (but push an empty string if value is NULL) */
  1514. pbx_builtin_pushvar_helper(chan, "VALUE", S_OR(a->argv[4], ""));
  1515. ast_str_substitute_variables(&sql, 0, chan, query->sql_write);
  1516. ast_debug(1, "SQL is %s\n", ast_str_buffer(sql));
  1517. chan = ast_channel_unref(chan);
  1518. if (a->argc == 6 && !strcmp(a->argv[5], "exec")) {
  1519. /* Execute the query */
  1520. struct odbc_obj *obj = NULL;
  1521. struct dsn *dsn = NULL;
  1522. int dsn_num, executed = 0;
  1523. SQLHSTMT stmt;
  1524. SQLLEN rows = -1;
  1525. for (dsn_num = 0; dsn_num < 5; dsn_num++) {
  1526. if (ast_strlen_zero(query->writehandle[dsn_num])) {
  1527. continue;
  1528. }
  1529. obj = get_odbc_obj(query->writehandle[dsn_num], &dsn);
  1530. if (!obj) {
  1531. continue;
  1532. }
  1533. if (!(stmt = ast_odbc_direct_execute(obj, generic_execute, ast_str_buffer(sql)))) {
  1534. release_obj_or_dsn (&obj, &dsn);
  1535. continue;
  1536. }
  1537. SQLRowCount(stmt, &rows);
  1538. SQLCloseCursor(stmt);
  1539. SQLFreeHandle(SQL_HANDLE_STMT, stmt);
  1540. release_obj_or_dsn (&obj, &dsn);
  1541. ast_cli(a->fd, "Affected %d rows. Query executed on handle %d [%s]\n", (int)rows, dsn_num, query->writehandle[dsn_num]);
  1542. executed = 1;
  1543. break;
  1544. }
  1545. if (!executed) {
  1546. ast_cli(a->fd, "Failed to execute query.\n");
  1547. }
  1548. } else { /* No execution, just print out the resulting SQL */
  1549. ast_cli(a->fd, "%s\n", ast_str_buffer(sql));
  1550. }
  1551. AST_RWLIST_UNLOCK(&queries);
  1552. return CLI_SUCCESS;
  1553. }
  1554. static struct ast_cli_entry cli_func_odbc[] = {
  1555. AST_CLI_DEFINE(cli_odbc_write, "Test setting a func_odbc function"),
  1556. AST_CLI_DEFINE(cli_odbc_read, "Test reading a func_odbc function"),
  1557. };
  1558. static int load_module(void)
  1559. {
  1560. int res = 0;
  1561. struct ast_config *cfg;
  1562. char *catg;
  1563. const char *s;
  1564. struct ast_flags config_flags = { 0 };
  1565. res |= ast_custom_function_register(&fetch_function);
  1566. res |= ast_register_application_xml(app_odbcfinish, exec_odbcfinish);
  1567. cfg = ast_config_load(config, config_flags);
  1568. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  1569. ast_log(LOG_NOTICE, "Unable to load config for func_odbc: %s\n", config);
  1570. return AST_MODULE_LOAD_DECLINE;
  1571. }
  1572. ast_rwlock_wrlock(&single_db_connection_lock);
  1573. if ((s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
  1574. single_db_connection = ast_true(s);
  1575. } else {
  1576. single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
  1577. }
  1578. dsns = NULL;
  1579. if (single_db_connection) {
  1580. dsns = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, DSN_BUCKETS,
  1581. dsn_hash, NULL, dsn_cmp);
  1582. if (!dsns) {
  1583. ast_log(LOG_ERROR, "Could not initialize DSN container\n");
  1584. ast_rwlock_unlock(&single_db_connection_lock);
  1585. return AST_MODULE_LOAD_DECLINE;
  1586. }
  1587. }
  1588. ast_rwlock_unlock(&single_db_connection_lock);
  1589. AST_RWLIST_WRLOCK(&queries);
  1590. for (catg = ast_category_browse(cfg, NULL);
  1591. catg;
  1592. catg = ast_category_browse(cfg, catg)) {
  1593. struct acf_odbc_query *query = NULL;
  1594. int err;
  1595. if (!strcasecmp(catg, "general")) {
  1596. continue;
  1597. }
  1598. if ((err = init_acf_query(cfg, catg, &query))) {
  1599. if (err == ENOMEM)
  1600. ast_log(LOG_ERROR, "Out of memory\n");
  1601. else if (err == EINVAL)
  1602. ast_log(LOG_ERROR, "Invalid parameters for category %s\n", catg);
  1603. else
  1604. ast_log(LOG_ERROR, "%s (%d)\n", strerror(err), err);
  1605. } else {
  1606. AST_RWLIST_INSERT_HEAD(&queries, query, list);
  1607. ast_custom_function_register(query->acf);
  1608. }
  1609. }
  1610. ast_config_destroy(cfg);
  1611. res |= ast_custom_function_register(&escape_function);
  1612. ast_cli_register_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
  1613. AST_RWLIST_UNLOCK(&queries);
  1614. return res;
  1615. }
  1616. static int unload_module(void)
  1617. {
  1618. struct acf_odbc_query *query;
  1619. int res = 0;
  1620. AST_RWLIST_WRLOCK(&queries);
  1621. while (!AST_RWLIST_EMPTY(&queries)) {
  1622. query = AST_RWLIST_REMOVE_HEAD(&queries, list);
  1623. ast_custom_function_unregister(query->acf);
  1624. free_acf_query(query);
  1625. }
  1626. res |= ast_custom_function_unregister(&escape_function);
  1627. res |= ast_custom_function_unregister(&fetch_function);
  1628. res |= ast_unregister_application(app_odbcfinish);
  1629. ast_cli_unregister_multiple(cli_func_odbc, ARRAY_LEN(cli_func_odbc));
  1630. /* Allow any threads waiting for this lock to pass (avoids a race) */
  1631. AST_RWLIST_UNLOCK(&queries);
  1632. usleep(1);
  1633. AST_RWLIST_WRLOCK(&queries);
  1634. AST_RWLIST_UNLOCK(&queries);
  1635. if (dsns) {
  1636. ao2_ref(dsns, -1);
  1637. }
  1638. return res;
  1639. }
  1640. static int reload(void)
  1641. {
  1642. int res = 0;
  1643. struct ast_config *cfg;
  1644. struct acf_odbc_query *oldquery;
  1645. char *catg;
  1646. const char *s;
  1647. struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
  1648. cfg = ast_config_load(config, config_flags);
  1649. if (cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
  1650. return 0;
  1651. ast_rwlock_wrlock(&single_db_connection_lock);
  1652. if (dsns) {
  1653. ao2_ref(dsns, -1);
  1654. dsns = NULL;
  1655. }
  1656. if (cfg && (s = ast_variable_retrieve(cfg, "general", "single_db_connection"))) {
  1657. single_db_connection = ast_true(s);
  1658. } else {
  1659. single_db_connection = DEFAULT_SINGLE_DB_CONNECTION;
  1660. }
  1661. if (single_db_connection) {
  1662. dsns = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, DSN_BUCKETS,
  1663. dsn_hash, NULL, dsn_cmp);
  1664. if (!dsns) {
  1665. ast_log(LOG_ERROR, "Could not initialize DSN container\n");
  1666. ast_rwlock_unlock(&single_db_connection_lock);
  1667. return 0;
  1668. }
  1669. }
  1670. ast_rwlock_unlock(&single_db_connection_lock);
  1671. AST_RWLIST_WRLOCK(&queries);
  1672. while (!AST_RWLIST_EMPTY(&queries)) {
  1673. oldquery = AST_RWLIST_REMOVE_HEAD(&queries, list);
  1674. ast_custom_function_unregister(oldquery->acf);
  1675. free_acf_query(oldquery);
  1676. }
  1677. if (!cfg) {
  1678. ast_log(LOG_WARNING, "Unable to load config for func_odbc: %s\n", config);
  1679. goto reload_out;
  1680. }
  1681. for (catg = ast_category_browse(cfg, NULL);
  1682. catg;
  1683. catg = ast_category_browse(cfg, catg)) {
  1684. struct acf_odbc_query *query = NULL;
  1685. if (!strcasecmp(catg, "general")) {
  1686. continue;
  1687. }
  1688. if (init_acf_query(cfg, catg, &query)) {
  1689. ast_log(LOG_ERROR, "Cannot initialize query %s\n", catg);
  1690. } else {
  1691. AST_RWLIST_INSERT_HEAD(&queries, query, list);
  1692. ast_custom_function_register(query->acf);
  1693. }
  1694. }
  1695. ast_config_destroy(cfg);
  1696. reload_out:
  1697. AST_RWLIST_UNLOCK(&queries);
  1698. return res;
  1699. }
  1700. /* XXX need to revise usecount - set if query_lock is set */
  1701. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ODBC lookups",
  1702. .support_level = AST_MODULE_SUPPORT_CORE,
  1703. .load = load_module,
  1704. .unload = unload_module,
  1705. .reload = reload,
  1706. );