res_config_sqlite.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2006, Proformatique
  5. *
  6. * Written by Richard Braun <rbraun@proformatique.com>
  7. *
  8. * Based on res_sqlite3 by Anthony Minessale II,
  9. * and res_config_mysql by Matthew Boehm
  10. *
  11. * See http://www.asterisk.org for more information about
  12. * the Asterisk project. Please do not directly contact
  13. * any of the maintainers of this project for assistance;
  14. * the project provides a web site, mailing lists and IRC
  15. * channels for your use.
  16. *
  17. * This program is free software, distributed under the terms of
  18. * the GNU General Public License Version 2. See the LICENSE file
  19. * at the top of the source tree.
  20. */
  21. /*!
  22. * \page res_config_sqlite
  23. *
  24. * \section intro_sec Presentation
  25. *
  26. * res_config_sqlite is a module for the Asterisk Open Source PBX to
  27. * support SQLite 2 databases. It can be used to fetch configuration
  28. * from a database (static configuration files and/or using the Asterisk
  29. * RealTime Architecture - ARA). It can also be used to log CDR entries.
  30. * Note that Asterisk already comes with a module named cdr_sqlite.
  31. * There are two reasons for including it in res_config_sqlite:
  32. * the first is that rewriting it was a training to learn how to write a
  33. * simple module for Asterisk, the other is to have the same database open for
  34. * all kinds of operations, which improves reliability and performance.
  35. *
  36. * \section conf_sec Configuration
  37. *
  38. * The main configuration file is res_config_sqlite.conf. It must be readable or
  39. * res_config_sqlite will fail to start. It is suggested to use the sample file
  40. * in this package as a starting point. The file has only one section
  41. * named <code>general</code>. Here are the supported parameters :
  42. *
  43. * <dl>
  44. * <dt><code>dbfile</code></dt>
  45. * <dd>The absolute path to the SQLite database (the file can be non existent,
  46. * res_config_sqlite will create it if it has the appropriate rights)</dd>
  47. * <dt><code>config_table</code></dt>
  48. * <dd>The table used for static configuration</dd>
  49. * <dt><code>cdr_table</code></dt>
  50. * <dd>The table used to store CDR entries (if ommitted, CDR support is
  51. * disabled)</dd>
  52. * </dl>
  53. *
  54. * To use res_config_sqlite for static and/or RealTime configuration, refer to the
  55. * Asterisk documentation. The file tables.sql can be used to create the
  56. * needed tables.
  57. *
  58. * \section status_sec Driver status
  59. *
  60. * The CLI command <code>show sqlite status</code> returns status information
  61. * about the running driver.
  62. *
  63. * \section credits_sec Credits
  64. *
  65. * res_config_sqlite was developed by Richard Braun at the Proformatique company.
  66. */
  67. /*!
  68. * \file
  69. * \brief res_config_sqlite module.
  70. */
  71. /*** MODULEINFO
  72. <depend>sqlite</depend>
  73. <support_level>extended</support_level>
  74. ***/
  75. #include "asterisk.h"
  76. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  77. #include <sqlite.h>
  78. #include "asterisk/logger.h"
  79. #include "asterisk/app.h"
  80. #include "asterisk/pbx.h"
  81. #include "asterisk/cdr.h"
  82. #include "asterisk/cli.h"
  83. #include "asterisk/lock.h"
  84. #include "asterisk/config.h"
  85. #include "asterisk/module.h"
  86. #include "asterisk/linkedlists.h"
  87. #define MACRO_BEGIN do {
  88. #define MACRO_END } while (0)
  89. #define RES_CONFIG_SQLITE_NAME "res_config_sqlite"
  90. #define RES_CONFIG_SQLITE_DRIVER "sqlite"
  91. #define RES_CONFIG_SQLITE_DESCRIPTION "Resource Module for SQLite 2"
  92. #define RES_CONFIG_SQLITE_CONF_FILE "res_config_sqlite.conf"
  93. enum {
  94. RES_CONFIG_SQLITE_CONFIG_ID,
  95. RES_CONFIG_SQLITE_CONFIG_CAT_METRIC,
  96. RES_CONFIG_SQLITE_CONFIG_VAR_METRIC,
  97. RES_CONFIG_SQLITE_CONFIG_COMMENTED,
  98. RES_CONFIG_SQLITE_CONFIG_FILENAME,
  99. RES_CONFIG_SQLITE_CONFIG_CATEGORY,
  100. RES_CONFIG_SQLITE_CONFIG_VAR_NAME,
  101. RES_CONFIG_SQLITE_CONFIG_VAR_VAL,
  102. RES_CONFIG_SQLITE_CONFIG_COLUMNS,
  103. };
  104. #define SET_VAR(config, to, from) \
  105. MACRO_BEGIN \
  106. int __error; \
  107. \
  108. __error = set_var(&to, #to, from->value); \
  109. \
  110. if (__error) { \
  111. ast_config_destroy(config); \
  112. unload_config(); \
  113. return 1; \
  114. } \
  115. MACRO_END
  116. AST_THREADSTORAGE(sql_buf);
  117. AST_THREADSTORAGE(where_buf);
  118. /*!
  119. * Maximum number of loops before giving up executing a query. Calls to
  120. * sqlite_xxx() functions which can return SQLITE_BUSY
  121. * are enclosed by RES_CONFIG_SQLITE_BEGIN and RES_CONFIG_SQLITE_END, e.g.
  122. * <pre>
  123. * char *errormsg;
  124. * int error;
  125. *
  126. * RES_CONFIG_SQLITE_BEGIN
  127. * error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  128. * RES_CONFIG_SQLITE_END(error)
  129. *
  130. * if (error)
  131. * ...;
  132. * </pre>
  133. */
  134. #define RES_CONFIG_SQLITE_MAX_LOOPS 10
  135. /*!
  136. * Macro used before executing a query.
  137. *
  138. * \see RES_CONFIG_SQLITE_MAX_LOOPS.
  139. */
  140. #define RES_CONFIG_SQLITE_BEGIN \
  141. MACRO_BEGIN \
  142. int __i; \
  143. \
  144. for (__i = 0; __i < RES_CONFIG_SQLITE_MAX_LOOPS; __i++) {
  145. /*!
  146. * Macro used after executing a query.
  147. *
  148. * \see RES_CONFIG_SQLITE_MAX_LOOPS.
  149. */
  150. #define RES_CONFIG_SQLITE_END(error) \
  151. if (error != SQLITE_BUSY) \
  152. break; \
  153. usleep(1000); \
  154. } \
  155. MACRO_END;
  156. /*!
  157. * Structure sent to the SQLite callback function for static configuration.
  158. *
  159. * \see add_cfg_entry()
  160. */
  161. struct cfg_entry_args {
  162. struct ast_config *cfg;
  163. struct ast_category *cat;
  164. char *cat_name;
  165. struct ast_flags flags;
  166. const char *who_asked;
  167. };
  168. /*!
  169. * Structure sent to the SQLite callback function for RealTime configuration.
  170. *
  171. * \see add_rt_cfg_entry()
  172. */
  173. struct rt_cfg_entry_args {
  174. struct ast_variable *var;
  175. struct ast_variable *last;
  176. };
  177. /*!
  178. * Structure sent to the SQLite callback function for RealTime configuration
  179. * (realtime_multi_handler()).
  180. *
  181. * \see add_rt_multi_cfg_entry()
  182. */
  183. struct rt_multi_cfg_entry_args {
  184. struct ast_config *cfg;
  185. char *initfield;
  186. };
  187. /*!
  188. * \brief Allocate a variable.
  189. * \param var the address of the variable to set (it will be allocated)
  190. * \param name the name of the variable (for error handling)
  191. * \param value the value to store in var
  192. * \retval 0 on success
  193. * \retval 1 if an allocation error occurred
  194. */
  195. static int set_var(char **var, const char *name, const char *value);
  196. /*!
  197. * \brief Load the configuration file.
  198. * \see unload_config()
  199. *
  200. * This function sets dbfile, config_table, and cdr_table. It calls
  201. * check_vars() before returning, and unload_config() if an error occurred.
  202. *
  203. * \retval 0 on success
  204. * \retval 1 if an error occurred
  205. */
  206. static int load_config(void);
  207. /*!
  208. * \brief Free resources related to configuration.
  209. * \see load_config()
  210. */
  211. static void unload_config(void);
  212. /*!
  213. * \brief Asterisk callback function for CDR support.
  214. * \param cdr the CDR entry Asterisk sends us.
  215. *
  216. * Asterisk will call this function each time a CDR entry must be logged if
  217. * CDR support is enabled.
  218. *
  219. * \retval 0 on success
  220. * \retval 1 if an error occurred
  221. */
  222. static int cdr_handler(struct ast_cdr *cdr);
  223. /*!
  224. * \brief SQLite callback function for static configuration.
  225. *
  226. * This function is passed to the SQLite engine as a callback function to
  227. * parse a row and store it in a struct ast_config object. It relies on
  228. * resulting rows being sorted by category.
  229. *
  230. * \param arg a pointer to a struct cfg_entry_args object
  231. * \param argc number of columns
  232. * \param argv values in the row
  233. * \param columnNames names and types of the columns
  234. * \retval 0 on success
  235. * \retval 1 if an error occurred
  236. * \see cfg_entry_args
  237. * \see sql_get_config_table
  238. * \see config_handler()
  239. */
  240. static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames);
  241. /*!
  242. * \brief Asterisk callback function for static configuration.
  243. *
  244. * Asterisk will call this function when it loads its static configuration,
  245. * which usually happens at startup and reload.
  246. *
  247. * \param database the database to use (ignored)
  248. * \param table the table to use
  249. * \param file the file to load from the database
  250. * \param cfg the struct ast_config object to use when storing variables
  251. * \param flags Optional flags. Not used.
  252. * \param suggested_incl suggest include.
  253. * \param who_asked
  254. * \retval cfg object
  255. * \retval NULL if an error occurred
  256. * \see add_cfg_entry()
  257. */
  258. static struct ast_config * config_handler(const char *database, const char *table, const char *file,
  259. struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked);
  260. /*!
  261. * \brief Helper function to parse a va_list object into 2 dynamic arrays of
  262. * strings, parameters and values.
  263. *
  264. * ap must have the following format : param1 val1 param2 val2 param3 val3 ...
  265. * arguments will be extracted to create 2 arrays:
  266. *
  267. * <ul>
  268. * <li>params : param1 param2 param3 ...</li>
  269. * <li>vals : val1 val2 val3 ...</li>
  270. * </ul>
  271. *
  272. * The address of these arrays are stored in params_ptr and vals_ptr. It
  273. * is the responsibility of the caller to release the memory of these arrays.
  274. * It is considered an error that va_list has a null or odd number of strings.
  275. *
  276. * \param ap the va_list object to parse
  277. * \param params_ptr where the address of the params array is stored
  278. * \param vals_ptr where the address of the vals array is stored
  279. * \param warn
  280. * \retval the number of elements in the arrays (which have the same size).
  281. * \retval 0 if an error occurred.
  282. */
  283. static size_t get_params(va_list ap, const char ***params_ptr,
  284. const char ***vals_ptr, int warn);
  285. /*!
  286. * \brief SQLite callback function for RealTime configuration.
  287. *
  288. * This function is passed to the SQLite engine as a callback function to
  289. * parse a row and store it in a linked list of struct ast_variable objects.
  290. *
  291. * \param arg a pointer to a struct rt_cfg_entry_args object
  292. * \param argc number of columns
  293. * \param argv values in the row
  294. * \param columnNames names and types of the columns
  295. * \retval 0 on success.
  296. * \retval 1 if an error occurred.
  297. * \see rt_cfg_entry_args
  298. * \see realtime_handler()
  299. */
  300. static int add_rt_cfg_entry(void *arg, int argc, char **argv,
  301. char **columnNames);
  302. /*!
  303. * \brief Asterisk callback function for RealTime configuration.
  304. *
  305. * Asterisk will call this function each time it requires a variable
  306. * through the RealTime architecture. ap is a list of parameters and
  307. * values used to find a specific row, e.g one parameter "name" and
  308. * one value "123" so that the SQL query becomes <code>SELECT * FROM
  309. * table WHERE name = '123';</code>.
  310. *
  311. * \param database the database to use (ignored)
  312. * \param table the table to use
  313. * \param ap list of parameters and values to match
  314. *
  315. * \retval a linked list of struct ast_variable objects
  316. * \retval NULL if an error occurred
  317. * \see add_rt_cfg_entry()
  318. */
  319. static struct ast_variable * realtime_handler(const char *database,
  320. const char *table, va_list ap);
  321. /*!
  322. * \brief SQLite callback function for RealTime configuration.
  323. *
  324. * This function performs the same actions as add_rt_cfg_entry() except
  325. * that the rt_multi_cfg_entry_args structure is designed to store
  326. * categories in addition to variables.
  327. *
  328. * \param arg a pointer to a struct rt_multi_cfg_entry_args object
  329. * \param argc number of columns
  330. * \param argv values in the row
  331. * \param columnNames names and types of the columns
  332. * \retval 0 on success.
  333. * \retval 1 if an error occurred.
  334. * \see rt_multi_cfg_entry_args
  335. * \see realtime_multi_handler()
  336. */
  337. static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv,
  338. char **columnNames);
  339. /*!
  340. * \brief Asterisk callback function for RealTime configuration.
  341. *
  342. * This function performs the same actions as realtime_handler() except
  343. * that it can store variables per category, and can return several
  344. * categories.
  345. *
  346. * \param database the database to use (ignored)
  347. * \param table the table to use
  348. * \param ap list of parameters and values to match
  349. * \retval a struct ast_config object storing categories and variables.
  350. * \retval NULL if an error occurred.
  351. *
  352. * \see add_rt_multi_cfg_entry()
  353. */
  354. static struct ast_config * realtime_multi_handler(const char *database,
  355. const char *table, va_list ap);
  356. /*!
  357. * \brief Asterisk callback function for RealTime configuration (variable
  358. * update).
  359. *
  360. * Asterisk will call this function each time a variable has been modified
  361. * internally and must be updated in the backend engine. keyfield and entity
  362. * are used to find the row to update, e.g. <code>UPDATE table SET ... WHERE
  363. * keyfield = 'entity';</code>. ap is a list of parameters and values with the
  364. * same format as the other realtime functions.
  365. *
  366. * \param database the database to use (ignored)
  367. * \param table the table to use
  368. * \param keyfield the column of the matching cell
  369. * \param entity the value of the matching cell
  370. * \param ap list of parameters and new values to update in the database
  371. * \retval the number of affected rows.
  372. * \retval -1 if an error occurred.
  373. */
  374. static int realtime_update_handler(const char *database, const char *table,
  375. const char *keyfield, const char *entity, va_list ap);
  376. static int realtime_update2_handler(const char *database, const char *table,
  377. va_list ap);
  378. /*!
  379. * \brief Asterisk callback function for RealTime configuration (variable
  380. * create/store).
  381. *
  382. * Asterisk will call this function each time a variable has been created
  383. * internally and must be stored in the backend engine.
  384. * are used to find the row to update, e.g. ap is a list of parameters and
  385. * values with the same format as the other realtime functions.
  386. *
  387. * \param database the database to use (ignored)
  388. * \param table the table to use
  389. * \param ap list of parameters and new values to insert into the database
  390. * \retval the rowid of inserted row.
  391. * \retval -1 if an error occurred.
  392. */
  393. static int realtime_store_handler(const char *database, const char *table,
  394. va_list ap);
  395. /*!
  396. * \brief Asterisk callback function for RealTime configuration (destroys
  397. * variable).
  398. *
  399. * Asterisk will call this function each time a variable has been destroyed
  400. * internally and must be removed from the backend engine. keyfield and entity
  401. * are used to find the row to delete, e.g. <code>DELETE FROM table WHERE
  402. * keyfield = 'entity';</code>. ap is a list of parameters and values with the
  403. * same format as the other realtime functions.
  404. *
  405. * \param database the database to use (ignored)
  406. * \param table the table to use
  407. * \param keyfield the column of the matching cell
  408. * \param entity the value of the matching cell
  409. * \param ap list of additional parameters for cell matching
  410. * \retval the number of affected rows.
  411. * \retval -1 if an error occurred.
  412. */
  413. static int realtime_destroy_handler(const char *database, const char *table,
  414. const char *keyfield, const char *entity, va_list ap);
  415. /*!
  416. * \brief Asterisk callback function for the CLI status command.
  417. *
  418. * \param e CLI command
  419. * \param cmd
  420. * \param a CLI argument list
  421. * \return RESULT_SUCCESS
  422. */
  423. static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  424. static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  425. static int realtime_require_handler(const char *database, const char *table, va_list ap);
  426. static int realtime_unload_handler(const char *unused, const char *tablename);
  427. /*! The SQLite database object. */
  428. static sqlite *db;
  429. /*! Set to 1 if CDR support is enabled. */
  430. static int use_cdr;
  431. /*! Set to 1 if the CDR callback function was registered. */
  432. static int cdr_registered;
  433. /*! Set to 1 if the CLI status command callback function was registered. */
  434. static int cli_status_registered;
  435. /*! The path of the database file. */
  436. static char *dbfile;
  437. /*! The name of the static configuration table. */
  438. static char *config_table;
  439. /*! The name of the table used to store CDR entries. */
  440. static char *cdr_table;
  441. /*!
  442. * The structure specifying all callback functions used by Asterisk for static
  443. * and RealTime configuration.
  444. */
  445. static struct ast_config_engine sqlite_engine =
  446. {
  447. .name = RES_CONFIG_SQLITE_DRIVER,
  448. .load_func = config_handler,
  449. .realtime_func = realtime_handler,
  450. .realtime_multi_func = realtime_multi_handler,
  451. .store_func = realtime_store_handler,
  452. .destroy_func = realtime_destroy_handler,
  453. .update_func = realtime_update_handler,
  454. .update2_func = realtime_update2_handler,
  455. .require_func = realtime_require_handler,
  456. .unload_func = realtime_unload_handler,
  457. };
  458. /*!
  459. * The mutex used to prevent simultaneous access to the SQLite database.
  460. */
  461. AST_MUTEX_DEFINE_STATIC(mutex);
  462. /*!
  463. * Structure containing details and callback functions for the CLI status
  464. * command.
  465. */
  466. static struct ast_cli_entry cli_status[] = {
  467. AST_CLI_DEFINE(handle_cli_show_sqlite_status, "Show status information about the SQLite 2 driver"),
  468. AST_CLI_DEFINE(handle_cli_sqlite_show_tables, "Cached table information about the SQLite 2 driver"),
  469. };
  470. struct sqlite_cache_columns {
  471. char *name;
  472. char *type;
  473. unsigned char isint; /*!< By definition, only INTEGER PRIMARY KEY is an integer; everything else is a string. */
  474. AST_RWLIST_ENTRY(sqlite_cache_columns) list;
  475. };
  476. struct sqlite_cache_tables {
  477. char *name;
  478. AST_RWLIST_HEAD(_columns, sqlite_cache_columns) columns;
  479. AST_RWLIST_ENTRY(sqlite_cache_tables) list;
  480. };
  481. static AST_RWLIST_HEAD_STATIC(sqlite_tables, sqlite_cache_tables);
  482. /*
  483. * Taken from Asterisk 1.2 cdr_sqlite.so.
  484. */
  485. /*! SQL query format to create the CDR table if non existent. */
  486. static char *sql_create_cdr_table =
  487. "CREATE TABLE '%q' (\n"
  488. " id INTEGER,\n"
  489. " clid VARCHAR(80) NOT NULL DEFAULT '',\n"
  490. " src VARCHAR(80) NOT NULL DEFAULT '',\n"
  491. " dst VARCHAR(80) NOT NULL DEFAULT '',\n"
  492. " dcontext VARCHAR(80) NOT NULL DEFAULT '',\n"
  493. " channel VARCHAR(80) NOT NULL DEFAULT '',\n"
  494. " dstchannel VARCHAR(80) NOT NULL DEFAULT '',\n"
  495. " lastapp VARCHAR(80) NOT NULL DEFAULT '',\n"
  496. " lastdata VARCHAR(80) NOT NULL DEFAULT '',\n"
  497. " start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
  498. " answer DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
  499. " end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n"
  500. " duration INT(11) NOT NULL DEFAULT 0,\n"
  501. " billsec INT(11) NOT NULL DEFAULT 0,\n"
  502. " disposition VARCHAR(45) NOT NULL DEFAULT '',\n"
  503. " amaflags INT(11) NOT NULL DEFAULT 0,\n"
  504. " accountcode VARCHAR(20) NOT NULL DEFAULT '',\n"
  505. " uniqueid VARCHAR(32) NOT NULL DEFAULT '',\n"
  506. " userfield VARCHAR(255) NOT NULL DEFAULT '',\n"
  507. " PRIMARY KEY (id)\n"
  508. ");";
  509. /*!
  510. * SQL query format to describe the table structure
  511. */
  512. #define sql_table_structure "SELECT sql FROM sqlite_master WHERE type='table' AND tbl_name='%s'"
  513. /*!
  514. * SQL query format to fetch the static configuration of a file.
  515. * Rows must be sorted by category.
  516. *
  517. * \see add_cfg_entry()
  518. */
  519. #define sql_get_config_table \
  520. "SELECT *" \
  521. " FROM '%q'" \
  522. " WHERE filename = '%q' AND commented = 0" \
  523. " ORDER BY cat_metric ASC, var_metric ASC;"
  524. static void free_table(struct sqlite_cache_tables *tblptr)
  525. {
  526. struct sqlite_cache_columns *col;
  527. /* Obtain a write lock to ensure there are no read locks outstanding */
  528. AST_RWLIST_WRLOCK(&(tblptr->columns));
  529. while ((col = AST_RWLIST_REMOVE_HEAD(&(tblptr->columns), list))) {
  530. ast_free(col);
  531. }
  532. AST_RWLIST_UNLOCK(&(tblptr->columns));
  533. AST_RWLIST_HEAD_DESTROY(&(tblptr->columns));
  534. ast_free(tblptr);
  535. }
  536. static int find_table_cb(void *vtblptr, int argc, char **argv, char **columnNames)
  537. {
  538. struct sqlite_cache_tables *tblptr = vtblptr;
  539. char *sql = ast_strdupa(argv[0]), *start, *end, *type, *remainder;
  540. int i;
  541. AST_DECLARE_APP_ARGS(fie,
  542. AST_APP_ARG(ld)[100]; /* This means we support up to 100 columns per table */
  543. );
  544. struct sqlite_cache_columns *col;
  545. /* This is really fun. We get to parse an SQL statement to figure out
  546. * what columns are in the table.
  547. */
  548. if ((start = strchr(sql, '(')) && (end = strrchr(sql, ')'))) {
  549. start++;
  550. *end = '\0';
  551. } else {
  552. /* Abort */
  553. return -1;
  554. }
  555. AST_STANDARD_APP_ARGS(fie, start);
  556. for (i = 0; i < fie.argc; i++) {
  557. fie.ld[i] = ast_skip_blanks(fie.ld[i]);
  558. ast_debug(5, "Found field: %s\n", fie.ld[i]);
  559. if (strncasecmp(fie.ld[i], "PRIMARY KEY", 11) == 0 && (start = strchr(fie.ld[i], '(')) && (end = strchr(fie.ld[i], ')'))) {
  560. *end = '\0';
  561. AST_RWLIST_TRAVERSE(&(tblptr->columns), col, list) {
  562. if (strcasecmp(start + 1, col->name) == 0 && strcasestr(col->type, "INTEGER")) {
  563. col->isint = 1;
  564. }
  565. }
  566. continue;
  567. }
  568. /* type delimiter could be any space character */
  569. for (type = fie.ld[i]; *type > 32; type++);
  570. *type++ = '\0';
  571. type = ast_skip_blanks(type);
  572. for (remainder = type; *remainder > 32; remainder++);
  573. *remainder = '\0';
  574. if (!(col = ast_calloc(1, sizeof(*col) + strlen(fie.ld[i]) + strlen(type) + 2))) {
  575. return -1;
  576. }
  577. col->name = (char *)col + sizeof(*col);
  578. col->type = (char *)col + sizeof(*col) + strlen(fie.ld[i]) + 1;
  579. strcpy(col->name, fie.ld[i]); /* SAFE */
  580. strcpy(col->type, type); /* SAFE */
  581. if (strcasestr(col->type, "INTEGER") && strcasestr(col->type, "PRIMARY KEY")) {
  582. col->isint = 1;
  583. }
  584. AST_LIST_INSERT_TAIL(&(tblptr->columns), col, list);
  585. }
  586. return 0;
  587. }
  588. static struct sqlite_cache_tables *find_table(const char *tablename)
  589. {
  590. struct sqlite_cache_tables *tblptr;
  591. int i, err;
  592. char *sql, *errstr = NULL;
  593. AST_RWLIST_RDLOCK(&sqlite_tables);
  594. for (i = 0; i < 2; i++) {
  595. AST_RWLIST_TRAVERSE(&sqlite_tables, tblptr, list) {
  596. if (strcmp(tblptr->name, tablename) == 0) {
  597. break;
  598. }
  599. }
  600. if (tblptr) {
  601. AST_RWLIST_RDLOCK(&(tblptr->columns));
  602. AST_RWLIST_UNLOCK(&sqlite_tables);
  603. return tblptr;
  604. }
  605. if (i == 0) {
  606. AST_RWLIST_UNLOCK(&sqlite_tables);
  607. AST_RWLIST_WRLOCK(&sqlite_tables);
  608. }
  609. }
  610. /* Table structure not cached; build the structure now */
  611. if (ast_asprintf(&sql, sql_table_structure, tablename) < 0) {
  612. sql = NULL;
  613. }
  614. if (!(tblptr = ast_calloc(1, sizeof(*tblptr) + strlen(tablename) + 1))) {
  615. AST_RWLIST_UNLOCK(&sqlite_tables);
  616. ast_log(LOG_ERROR, "Memory error. Cannot cache table '%s'\n", tablename);
  617. ast_free(sql);
  618. return NULL;
  619. }
  620. tblptr->name = (char *)tblptr + sizeof(*tblptr);
  621. strcpy(tblptr->name, tablename); /* SAFE */
  622. AST_RWLIST_HEAD_INIT(&(tblptr->columns));
  623. ast_debug(1, "About to query table structure: %s\n", sql);
  624. ast_mutex_lock(&mutex);
  625. if ((err = sqlite_exec(db, sql, find_table_cb, tblptr, &errstr))) {
  626. ast_mutex_unlock(&mutex);
  627. ast_log(LOG_WARNING, "SQLite error %d: %s\n", err, errstr);
  628. ast_free(errstr);
  629. free_table(tblptr);
  630. AST_RWLIST_UNLOCK(&sqlite_tables);
  631. ast_free(sql);
  632. return NULL;
  633. }
  634. ast_mutex_unlock(&mutex);
  635. ast_free(sql);
  636. if (AST_LIST_EMPTY(&(tblptr->columns))) {
  637. free_table(tblptr);
  638. AST_RWLIST_UNLOCK(&sqlite_tables);
  639. return NULL;
  640. }
  641. AST_RWLIST_INSERT_TAIL(&sqlite_tables, tblptr, list);
  642. AST_RWLIST_RDLOCK(&(tblptr->columns));
  643. AST_RWLIST_UNLOCK(&sqlite_tables);
  644. return tblptr;
  645. }
  646. #define release_table(a) AST_RWLIST_UNLOCK(&((a)->columns))
  647. static int set_var(char **var, const char *name, const char *value)
  648. {
  649. if (*var)
  650. ast_free(*var);
  651. *var = ast_strdup(value);
  652. if (!*var) {
  653. ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
  654. return 1;
  655. }
  656. return 0;
  657. }
  658. static int check_vars(void)
  659. {
  660. if (!dbfile) {
  661. ast_log(LOG_ERROR, "Required parameter undefined: dbfile\n");
  662. return 1;
  663. }
  664. use_cdr = (cdr_table != NULL);
  665. return 0;
  666. }
  667. static int load_config(void)
  668. {
  669. struct ast_config *config;
  670. struct ast_variable *var;
  671. int error;
  672. struct ast_flags config_flags = { 0 };
  673. config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
  674. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  675. ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
  676. return 1;
  677. }
  678. for (var = ast_variable_browse(config, "general"); var; var = var->next) {
  679. if (!strcasecmp(var->name, "dbfile"))
  680. SET_VAR(config, dbfile, var);
  681. else if (!strcasecmp(var->name, "config_table"))
  682. SET_VAR(config, config_table, var);
  683. else if (!strcasecmp(var->name, "cdr_table")) {
  684. SET_VAR(config, cdr_table, var);
  685. } else
  686. ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
  687. }
  688. ast_config_destroy(config);
  689. error = check_vars();
  690. if (error) {
  691. unload_config();
  692. return 1;
  693. }
  694. return 0;
  695. }
  696. static void unload_config(void)
  697. {
  698. struct sqlite_cache_tables *tbl;
  699. ast_free(dbfile);
  700. dbfile = NULL;
  701. ast_free(config_table);
  702. config_table = NULL;
  703. ast_free(cdr_table);
  704. cdr_table = NULL;
  705. AST_RWLIST_WRLOCK(&sqlite_tables);
  706. while ((tbl = AST_RWLIST_REMOVE_HEAD(&sqlite_tables, list))) {
  707. free_table(tbl);
  708. }
  709. AST_RWLIST_UNLOCK(&sqlite_tables);
  710. }
  711. static int cdr_handler(struct ast_cdr *cdr)
  712. {
  713. char *errormsg = NULL, *tmp, workspace[500];
  714. int error, scannum;
  715. struct sqlite_cache_tables *tbl = find_table(cdr_table);
  716. struct sqlite_cache_columns *col;
  717. struct ast_str *sql1 = ast_str_create(160), *sql2 = ast_str_create(16);
  718. int first = 1;
  719. if (!tbl) {
  720. ast_log(LOG_WARNING, "No such table: %s\n", cdr_table);
  721. return -1;
  722. }
  723. ast_str_set(&sql1, 0, "INSERT INTO %s (", cdr_table);
  724. ast_str_set(&sql2, 0, ") VALUES (");
  725. AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
  726. if (col->isint) {
  727. ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 1);
  728. if (!tmp) {
  729. continue;
  730. }
  731. if (sscanf(tmp, "%30d", &scannum) == 1) {
  732. ast_str_append(&sql1, 0, "%s%s", first ? "" : ",", col->name);
  733. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", scannum);
  734. }
  735. } else {
  736. ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 0);
  737. if (!tmp) {
  738. continue;
  739. }
  740. ast_str_append(&sql1, 0, "%s%s", first ? "" : ",", col->name);
  741. tmp = sqlite_mprintf("%Q", tmp);
  742. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", tmp);
  743. sqlite_freemem(tmp);
  744. }
  745. first = 0;
  746. }
  747. release_table(tbl);
  748. ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
  749. ast_free(sql2);
  750. ast_debug(1, "SQL query: %s\n", ast_str_buffer(sql1));
  751. ast_mutex_lock(&mutex);
  752. RES_CONFIG_SQLITE_BEGIN
  753. error = sqlite_exec(db, ast_str_buffer(sql1), NULL, NULL, &errormsg);
  754. RES_CONFIG_SQLITE_END(error)
  755. ast_mutex_unlock(&mutex);
  756. ast_free(sql1);
  757. if (error) {
  758. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  759. sqlite_freemem(errormsg);
  760. return 1;
  761. }
  762. sqlite_freemem(errormsg);
  763. return 0;
  764. }
  765. static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  766. {
  767. struct cfg_entry_args *args;
  768. struct ast_variable *var;
  769. if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
  770. ast_log(LOG_WARNING, "Corrupt table\n");
  771. return 1;
  772. }
  773. args = arg;
  774. if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
  775. struct ast_config *cfg;
  776. char *val;
  777. val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
  778. cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
  779. if (!cfg) {
  780. ast_log(LOG_WARNING, "Unable to include %s\n", val);
  781. return 1;
  782. } else {
  783. args->cfg = cfg;
  784. return 0;
  785. }
  786. }
  787. if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
  788. args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
  789. if (!args->cat) {
  790. ast_log(LOG_WARNING, "Unable to allocate category\n");
  791. return 1;
  792. }
  793. ast_free(args->cat_name);
  794. args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
  795. if (!args->cat_name) {
  796. ast_category_destroy(args->cat);
  797. return 1;
  798. }
  799. ast_category_append(args->cfg, args->cat);
  800. }
  801. var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
  802. if (!var) {
  803. ast_log(LOG_WARNING, "Unable to allocate variable\n");
  804. return 1;
  805. }
  806. ast_variable_append(args->cat, var);
  807. return 0;
  808. }
  809. static struct ast_config *config_handler(const char *database, const char *table, const char *file,
  810. struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
  811. {
  812. struct cfg_entry_args args;
  813. char *query, *errormsg = NULL;
  814. int error;
  815. if (!config_table) {
  816. if (!table) {
  817. ast_log(LOG_ERROR, "Table name unspecified\n");
  818. return NULL;
  819. }
  820. } else
  821. table = config_table;
  822. query = sqlite_mprintf(sql_get_config_table, table, file);
  823. if (!query) {
  824. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  825. return NULL;
  826. }
  827. ast_debug(1, "SQL query: %s\n", query);
  828. args.cfg = cfg;
  829. args.cat = NULL;
  830. args.cat_name = NULL;
  831. args.flags = flags;
  832. args.who_asked = who_asked;
  833. ast_mutex_lock(&mutex);
  834. RES_CONFIG_SQLITE_BEGIN
  835. error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
  836. RES_CONFIG_SQLITE_END(error)
  837. ast_mutex_unlock(&mutex);
  838. ast_free(args.cat_name);
  839. sqlite_freemem(query);
  840. if (error) {
  841. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  842. sqlite_freemem(errormsg);
  843. return NULL;
  844. }
  845. sqlite_freemem(errormsg);
  846. return cfg;
  847. }
  848. static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr, int warn)
  849. {
  850. const char **tmp, *param, *val, **params, **vals;
  851. size_t params_count;
  852. params = NULL;
  853. vals = NULL;
  854. params_count = 0;
  855. while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
  856. if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
  857. ast_free(params);
  858. ast_free(vals);
  859. return 0;
  860. }
  861. params = tmp;
  862. if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
  863. ast_free(params);
  864. ast_free(vals);
  865. return 0;
  866. }
  867. vals = tmp;
  868. params[params_count] = param;
  869. vals[params_count] = val;
  870. params_count++;
  871. }
  872. if (params_count > 0) {
  873. *params_ptr = params;
  874. *vals_ptr = vals;
  875. } else if (warn) {
  876. ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
  877. }
  878. return params_count;
  879. }
  880. static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  881. {
  882. struct rt_cfg_entry_args *args;
  883. struct ast_variable *var;
  884. int i;
  885. args = arg;
  886. for (i = 0; i < argc; i++) {
  887. if (!argv[i])
  888. continue;
  889. if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
  890. return 1;
  891. if (!args->var)
  892. args->var = var;
  893. if (!args->last)
  894. args->last = var;
  895. else {
  896. args->last->next = var;
  897. args->last = var;
  898. }
  899. }
  900. return 0;
  901. }
  902. static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
  903. {
  904. char *query, *errormsg = NULL, *op, *tmp_str;
  905. struct rt_cfg_entry_args args;
  906. const char **params, **vals;
  907. size_t params_count;
  908. int error;
  909. if (!table) {
  910. ast_log(LOG_WARNING, "Table name unspecified\n");
  911. return NULL;
  912. }
  913. params_count = get_params(ap, &params, &vals, 1);
  914. if (params_count == 0)
  915. return NULL;
  916. op = (strchr(params[0], ' ') == NULL) ? " =" : "";
  917. /* \cond DOXYGEN_CAN_PARSE_THIS */
  918. #undef QUERY
  919. #define QUERY "SELECT * FROM '%q' WHERE%s %q%s '%q'"
  920. /* \endcond */
  921. query = sqlite_mprintf(QUERY, table, (config_table && !strcmp(config_table, table)) ? " commented = 0 AND" : "", params[0], op, vals[0]);
  922. if (!query) {
  923. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  924. ast_free(params);
  925. ast_free(vals);
  926. return NULL;
  927. }
  928. if (params_count > 1) {
  929. size_t i;
  930. for (i = 1; i < params_count; i++) {
  931. op = (strchr(params[i], ' ') == NULL) ? " =" : "";
  932. tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
  933. sqlite_freemem(query);
  934. if (!tmp_str) {
  935. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  936. ast_free(params);
  937. ast_free(vals);
  938. return NULL;
  939. }
  940. query = tmp_str;
  941. }
  942. }
  943. ast_free(params);
  944. ast_free(vals);
  945. tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
  946. sqlite_freemem(query);
  947. if (!tmp_str) {
  948. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  949. return NULL;
  950. }
  951. query = tmp_str;
  952. ast_debug(1, "SQL query: %s\n", query);
  953. args.var = NULL;
  954. args.last = NULL;
  955. ast_mutex_lock(&mutex);
  956. RES_CONFIG_SQLITE_BEGIN
  957. error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
  958. RES_CONFIG_SQLITE_END(error)
  959. ast_mutex_unlock(&mutex);
  960. sqlite_freemem(query);
  961. if (error) {
  962. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  963. sqlite_freemem(errormsg);
  964. ast_variables_destroy(args.var);
  965. return NULL;
  966. }
  967. sqlite_freemem(errormsg);
  968. return args.var;
  969. }
  970. static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  971. {
  972. struct rt_multi_cfg_entry_args *args;
  973. struct ast_category *cat;
  974. struct ast_variable *var;
  975. char *cat_name;
  976. size_t i;
  977. args = arg;
  978. cat_name = NULL;
  979. /*
  980. * cat_name should always be set here, since initfield is forged from
  981. * params[0] in realtime_multi_handler(), which is a search parameter
  982. * of the SQL query.
  983. */
  984. for (i = 0; i < argc; i++) {
  985. if (!strcmp(args->initfield, columnNames[i]))
  986. cat_name = argv[i];
  987. }
  988. if (!cat_name) {
  989. ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
  990. return 1;
  991. }
  992. if (!(cat = ast_category_new(cat_name, "", 99999))) {
  993. ast_log(LOG_WARNING, "Unable to allocate category\n");
  994. return 1;
  995. }
  996. ast_category_append(args->cfg, cat);
  997. for (i = 0; i < argc; i++) {
  998. if (!argv[i]) {
  999. continue;
  1000. }
  1001. if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
  1002. ast_log(LOG_WARNING, "Unable to allocate variable\n");
  1003. return 1;
  1004. }
  1005. ast_variable_append(cat, var);
  1006. }
  1007. return 0;
  1008. }
  1009. static struct ast_config *realtime_multi_handler(const char *database,
  1010. const char *table, va_list ap)
  1011. {
  1012. char *query, *errormsg = NULL, *op, *tmp_str, *initfield;
  1013. struct rt_multi_cfg_entry_args args;
  1014. const char **params, **vals;
  1015. struct ast_config *cfg;
  1016. size_t params_count;
  1017. int error;
  1018. if (!table) {
  1019. ast_log(LOG_WARNING, "Table name unspecified\n");
  1020. return NULL;
  1021. }
  1022. if (!(cfg = ast_config_new())) {
  1023. ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
  1024. return NULL;
  1025. }
  1026. if (!(params_count = get_params(ap, &params, &vals, 1))) {
  1027. ast_config_destroy(cfg);
  1028. return NULL;
  1029. }
  1030. if (!(initfield = ast_strdup(params[0]))) {
  1031. ast_config_destroy(cfg);
  1032. ast_free(params);
  1033. ast_free(vals);
  1034. return NULL;
  1035. }
  1036. tmp_str = strchr(initfield, ' ');
  1037. if (tmp_str)
  1038. *tmp_str = '\0';
  1039. op = (!strchr(params[0], ' ')) ? " =" : "";
  1040. /*
  1041. * Asterisk sends us an already escaped string when searching for
  1042. * "exten LIKE" (uh!). Handle it separately.
  1043. */
  1044. tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
  1045. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1046. #undef QUERY
  1047. #define QUERY "SELECT * FROM '%q' WHERE%s %q%s '%q'"
  1048. /* \endcond */
  1049. if (!(query = sqlite_mprintf(QUERY, table, (config_table && !strcmp(config_table, table)) ? " commented = 0 AND" : "", params[0], op, tmp_str))) {
  1050. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1051. ast_config_destroy(cfg);
  1052. ast_free(params);
  1053. ast_free(vals);
  1054. ast_free(initfield);
  1055. return NULL;
  1056. }
  1057. if (params_count > 1) {
  1058. size_t i;
  1059. for (i = 1; i < params_count; i++) {
  1060. op = (!strchr(params[i], ' ')) ? " =" : "";
  1061. tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
  1062. sqlite_freemem(query);
  1063. if (!tmp_str) {
  1064. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1065. ast_config_destroy(cfg);
  1066. ast_free(params);
  1067. ast_free(vals);
  1068. ast_free(initfield);
  1069. return NULL;
  1070. }
  1071. query = tmp_str;
  1072. }
  1073. }
  1074. ast_free(params);
  1075. ast_free(vals);
  1076. if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
  1077. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1078. sqlite_freemem(query);
  1079. ast_config_destroy(cfg);
  1080. ast_free(initfield);
  1081. return NULL;
  1082. }
  1083. sqlite_freemem(query);
  1084. query = tmp_str;
  1085. ast_debug(1, "SQL query: %s\n", query);
  1086. args.cfg = cfg;
  1087. args.initfield = initfield;
  1088. ast_mutex_lock(&mutex);
  1089. RES_CONFIG_SQLITE_BEGIN
  1090. error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
  1091. RES_CONFIG_SQLITE_END(error)
  1092. ast_mutex_unlock(&mutex);
  1093. sqlite_freemem(query);
  1094. ast_free(initfield);
  1095. if (error) {
  1096. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1097. sqlite_freemem(errormsg);
  1098. ast_config_destroy(cfg);
  1099. return NULL;
  1100. }
  1101. sqlite_freemem(errormsg);
  1102. return cfg;
  1103. }
  1104. static int realtime_update_handler(const char *database, const char *table,
  1105. const char *keyfield, const char *entity, va_list ap)
  1106. {
  1107. char *query, *errormsg = NULL, *tmp_str;
  1108. const char **params, **vals;
  1109. size_t params_count;
  1110. int error, rows_num;
  1111. if (!table) {
  1112. ast_log(LOG_WARNING, "Table name unspecified\n");
  1113. return -1;
  1114. }
  1115. if (!(params_count = get_params(ap, &params, &vals, 1)))
  1116. return -1;
  1117. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1118. #undef QUERY
  1119. #define QUERY "UPDATE '%q' SET %q = '%q'"
  1120. /* \endcond */
  1121. if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
  1122. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1123. ast_free(params);
  1124. ast_free(vals);
  1125. return -1;
  1126. }
  1127. if (params_count > 1) {
  1128. size_t i;
  1129. for (i = 1; i < params_count; i++) {
  1130. tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
  1131. sqlite_freemem(query);
  1132. if (!tmp_str) {
  1133. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1134. ast_free(params);
  1135. ast_free(vals);
  1136. return -1;
  1137. }
  1138. query = tmp_str;
  1139. }
  1140. }
  1141. ast_free(params);
  1142. ast_free(vals);
  1143. if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
  1144. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1145. sqlite_freemem(query);
  1146. return -1;
  1147. }
  1148. sqlite_freemem(query);
  1149. query = tmp_str;
  1150. ast_debug(1, "SQL query: %s\n", query);
  1151. ast_mutex_lock(&mutex);
  1152. RES_CONFIG_SQLITE_BEGIN
  1153. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1154. RES_CONFIG_SQLITE_END(error)
  1155. if (!error)
  1156. rows_num = sqlite_changes(db);
  1157. else
  1158. rows_num = -1;
  1159. ast_mutex_unlock(&mutex);
  1160. sqlite_freemem(query);
  1161. if (error) {
  1162. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1163. }
  1164. sqlite_freemem(errormsg);
  1165. return rows_num;
  1166. }
  1167. static int realtime_update2_handler(const char *database, const char *table,
  1168. va_list ap)
  1169. {
  1170. char *errormsg = NULL, *tmp1, *tmp2;
  1171. int error, rows_num, first = 1;
  1172. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  1173. struct ast_str *where = ast_str_thread_get(&where_buf, 100);
  1174. const char *param, *value;
  1175. if (!table) {
  1176. ast_log(LOG_WARNING, "Table name unspecified\n");
  1177. return -1;
  1178. }
  1179. if (!sql) {
  1180. return -1;
  1181. }
  1182. ast_str_set(&sql, 0, "UPDATE %s SET", table);
  1183. ast_str_set(&where, 0, " WHERE");
  1184. while ((param = va_arg(ap, const char *))) {
  1185. value = va_arg(ap, const char *);
  1186. ast_str_append(&where, 0, "%s %s = %s",
  1187. first ? "" : " AND",
  1188. tmp1 = sqlite_mprintf("%q", param),
  1189. tmp2 = sqlite_mprintf("%Q", value));
  1190. sqlite_freemem(tmp1);
  1191. sqlite_freemem(tmp2);
  1192. first = 0;
  1193. }
  1194. if (first) {
  1195. ast_log(LOG_ERROR, "No criteria specified on update to '%s@%s'!\n", table, database);
  1196. return -1;
  1197. }
  1198. first = 1;
  1199. while ((param = va_arg(ap, const char *))) {
  1200. value = va_arg(ap, const char *);
  1201. ast_str_append(&sql, 0, "%s %s = %s",
  1202. first ? "" : ",",
  1203. tmp1 = sqlite_mprintf("%q", param),
  1204. tmp2 = sqlite_mprintf("%Q", value));
  1205. sqlite_freemem(tmp1);
  1206. sqlite_freemem(tmp2);
  1207. first = 0;
  1208. }
  1209. ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
  1210. ast_debug(1, "SQL query: %s\n", ast_str_buffer(sql));
  1211. ast_mutex_lock(&mutex);
  1212. RES_CONFIG_SQLITE_BEGIN
  1213. error = sqlite_exec(db, ast_str_buffer(sql), NULL, NULL, &errormsg);
  1214. RES_CONFIG_SQLITE_END(error)
  1215. if (!error) {
  1216. rows_num = sqlite_changes(db);
  1217. } else {
  1218. rows_num = -1;
  1219. }
  1220. ast_mutex_unlock(&mutex);
  1221. if (error) {
  1222. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1223. }
  1224. sqlite_freemem(errormsg);
  1225. return rows_num;
  1226. }
  1227. static int realtime_store_handler(const char *database, const char *table, va_list ap)
  1228. {
  1229. char *errormsg = NULL, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
  1230. const char **params, **vals;
  1231. size_t params_count;
  1232. int error, rows_id;
  1233. size_t i;
  1234. if (!table) {
  1235. ast_log(LOG_WARNING, "Table name unspecified\n");
  1236. return -1;
  1237. }
  1238. if (!(params_count = get_params(ap, &params, &vals, 1)))
  1239. return -1;
  1240. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1241. #undef QUERY
  1242. #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
  1243. /* \endcond */
  1244. for (i = 0; i < params_count; i++) {
  1245. if ( tmp_keys2 ) {
  1246. tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
  1247. sqlite_freemem(tmp_keys2);
  1248. } else {
  1249. tmp_keys = sqlite_mprintf("%q", params[i]);
  1250. }
  1251. if (!tmp_keys) {
  1252. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1253. sqlite_freemem(tmp_vals);
  1254. ast_free(params);
  1255. ast_free(vals);
  1256. return -1;
  1257. }
  1258. if ( tmp_vals2 ) {
  1259. tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, vals[i]);
  1260. sqlite_freemem(tmp_vals2);
  1261. } else {
  1262. tmp_vals = sqlite_mprintf("'%q'", vals[i]);
  1263. }
  1264. if (!tmp_vals) {
  1265. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1266. sqlite_freemem(tmp_keys);
  1267. ast_free(params);
  1268. ast_free(vals);
  1269. return -1;
  1270. }
  1271. tmp_keys2 = tmp_keys;
  1272. tmp_vals2 = tmp_vals;
  1273. }
  1274. ast_free(params);
  1275. ast_free(vals);
  1276. if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
  1277. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1278. sqlite_freemem(tmp_keys);
  1279. sqlite_freemem(tmp_vals);
  1280. return -1;
  1281. }
  1282. sqlite_freemem(tmp_keys);
  1283. sqlite_freemem(tmp_vals);
  1284. ast_debug(1, "SQL query: %s\n", tmp_str);
  1285. ast_mutex_lock(&mutex);
  1286. RES_CONFIG_SQLITE_BEGIN
  1287. error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
  1288. RES_CONFIG_SQLITE_END(error)
  1289. if (!error) {
  1290. rows_id = sqlite_last_insert_rowid(db);
  1291. } else {
  1292. rows_id = -1;
  1293. }
  1294. ast_mutex_unlock(&mutex);
  1295. sqlite_freemem(tmp_str);
  1296. if (error) {
  1297. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1298. }
  1299. sqlite_freemem(errormsg);
  1300. return rows_id;
  1301. }
  1302. static int realtime_destroy_handler(const char *database, const char *table,
  1303. const char *keyfield, const char *entity, va_list ap)
  1304. {
  1305. char *query, *errormsg = NULL, *tmp_str;
  1306. const char **params = NULL, **vals = NULL;
  1307. size_t params_count;
  1308. int error, rows_num;
  1309. size_t i;
  1310. if (!table) {
  1311. ast_log(LOG_WARNING, "Table name unspecified\n");
  1312. return -1;
  1313. }
  1314. params_count = get_params(ap, &params, &vals, 0);
  1315. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1316. #undef QUERY
  1317. #define QUERY "DELETE FROM '%q' WHERE"
  1318. /* \endcond */
  1319. if (!(query = sqlite_mprintf(QUERY, table))) {
  1320. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1321. ast_free(params);
  1322. ast_free(vals);
  1323. return -1;
  1324. }
  1325. for (i = 0; i < params_count; i++) {
  1326. tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
  1327. sqlite_freemem(query);
  1328. if (!tmp_str) {
  1329. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1330. ast_free(params);
  1331. ast_free(vals);
  1332. return -1;
  1333. }
  1334. query = tmp_str;
  1335. }
  1336. ast_free(params);
  1337. ast_free(vals);
  1338. if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
  1339. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1340. sqlite_freemem(query);
  1341. return -1;
  1342. }
  1343. sqlite_freemem(query);
  1344. query = tmp_str;
  1345. ast_debug(1, "SQL query: %s\n", query);
  1346. ast_mutex_lock(&mutex);
  1347. RES_CONFIG_SQLITE_BEGIN
  1348. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1349. RES_CONFIG_SQLITE_END(error)
  1350. if (!error) {
  1351. rows_num = sqlite_changes(db);
  1352. } else {
  1353. rows_num = -1;
  1354. }
  1355. ast_mutex_unlock(&mutex);
  1356. sqlite_freemem(query);
  1357. if (error) {
  1358. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1359. }
  1360. sqlite_freemem(errormsg);
  1361. return rows_num;
  1362. }
  1363. static int realtime_require_handler(const char *unused, const char *tablename, va_list ap)
  1364. {
  1365. struct sqlite_cache_tables *tbl = find_table(tablename);
  1366. struct sqlite_cache_columns *col;
  1367. char *elm;
  1368. int type, res = 0;
  1369. if (!tbl) {
  1370. return -1;
  1371. }
  1372. while ((elm = va_arg(ap, char *))) {
  1373. type = va_arg(ap, require_type);
  1374. va_arg(ap, int);
  1375. /* Check if the field matches the criteria */
  1376. AST_RWLIST_TRAVERSE(&tbl->columns, col, list) {
  1377. if (strcmp(col->name, elm) == 0) {
  1378. /* SQLite only has two types - the 32-bit integer field that
  1379. * is the key column, and everything else (everything else
  1380. * being a string).
  1381. */
  1382. if (col->isint && !ast_rq_is_int(type)) {
  1383. ast_log(LOG_WARNING, "Realtime table %s: column '%s' is an integer field, but Asterisk requires that it not be!\n", tablename, col->name);
  1384. res = -1;
  1385. }
  1386. break;
  1387. }
  1388. }
  1389. if (!col) {
  1390. ast_log(LOG_WARNING, "Realtime table %s requires column '%s', but that column does not exist!\n", tablename, elm);
  1391. }
  1392. }
  1393. AST_RWLIST_UNLOCK(&(tbl->columns));
  1394. return res;
  1395. }
  1396. static int realtime_unload_handler(const char *unused, const char *tablename)
  1397. {
  1398. struct sqlite_cache_tables *tbl;
  1399. AST_RWLIST_WRLOCK(&sqlite_tables);
  1400. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sqlite_tables, tbl, list) {
  1401. if (!strcasecmp(tbl->name, tablename)) {
  1402. AST_RWLIST_REMOVE_CURRENT(list);
  1403. free_table(tbl);
  1404. }
  1405. }
  1406. AST_RWLIST_TRAVERSE_SAFE_END
  1407. AST_RWLIST_UNLOCK(&sqlite_tables);
  1408. return 0;
  1409. }
  1410. static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1411. {
  1412. switch (cmd) {
  1413. case CLI_INIT:
  1414. e->command = "sqlite show status";
  1415. e->usage =
  1416. "Usage: sqlite show status\n"
  1417. " Show status information about the SQLite 2 driver\n";
  1418. return NULL;
  1419. case CLI_GENERATE:
  1420. return NULL;
  1421. }
  1422. if (a->argc != 3)
  1423. return CLI_SHOWUSAGE;
  1424. ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
  1425. ast_cli(a->fd, "config_table: ");
  1426. if (!config_table)
  1427. ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
  1428. else
  1429. ast_cli(a->fd, "%s\n", config_table);
  1430. ast_cli(a->fd, "cdr_table: ");
  1431. if (!cdr_table)
  1432. ast_cli(a->fd, "unspecified, CDR support disabled\n");
  1433. else
  1434. ast_cli(a->fd, "%s\n", cdr_table);
  1435. return CLI_SUCCESS;
  1436. }
  1437. static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1438. {
  1439. struct sqlite_cache_tables *tbl;
  1440. struct sqlite_cache_columns *col;
  1441. int found = 0;
  1442. switch (cmd) {
  1443. case CLI_INIT:
  1444. e->command = "sqlite show tables";
  1445. e->usage =
  1446. "Usage: sqlite show tables\n"
  1447. " Show table information about the SQLite 2 driver\n";
  1448. return NULL;
  1449. case CLI_GENERATE:
  1450. return NULL;
  1451. }
  1452. if (a->argc != 3)
  1453. return CLI_SHOWUSAGE;
  1454. AST_RWLIST_RDLOCK(&sqlite_tables);
  1455. AST_RWLIST_TRAVERSE(&sqlite_tables, tbl, list) {
  1456. found++;
  1457. ast_cli(a->fd, "Table %s:\n", tbl->name);
  1458. AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
  1459. fprintf(stderr, "%s\n", col->name);
  1460. ast_cli(a->fd, " %20.20s %-30.30s\n", col->name, col->type);
  1461. }
  1462. }
  1463. AST_RWLIST_UNLOCK(&sqlite_tables);
  1464. if (!found) {
  1465. ast_cli(a->fd, "No tables currently in cache\n");
  1466. }
  1467. return CLI_SUCCESS;
  1468. }
  1469. static int unload_module(void)
  1470. {
  1471. if (cli_status_registered)
  1472. ast_cli_unregister_multiple(cli_status, ARRAY_LEN(cli_status));
  1473. if (cdr_registered)
  1474. ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
  1475. ast_config_engine_deregister(&sqlite_engine);
  1476. if (db)
  1477. sqlite_close(db);
  1478. unload_config();
  1479. return 0;
  1480. }
  1481. static int load_module(void)
  1482. {
  1483. char *errormsg = NULL;
  1484. int error;
  1485. db = NULL;
  1486. cdr_registered = 0;
  1487. cli_status_registered = 0;
  1488. dbfile = NULL;
  1489. config_table = NULL;
  1490. cdr_table = NULL;
  1491. error = load_config();
  1492. if (error)
  1493. return AST_MODULE_LOAD_DECLINE;
  1494. if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
  1495. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1496. sqlite_freemem(errormsg);
  1497. unload_module();
  1498. return 1;
  1499. }
  1500. sqlite_freemem(errormsg);
  1501. errormsg = NULL;
  1502. ast_config_engine_register(&sqlite_engine);
  1503. if (use_cdr) {
  1504. char *query;
  1505. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1506. #undef QUERY
  1507. #define QUERY "SELECT COUNT(id) FROM %Q;"
  1508. /* \endcond */
  1509. query = sqlite_mprintf(QUERY, cdr_table);
  1510. if (!query) {
  1511. ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
  1512. unload_module();
  1513. return 1;
  1514. }
  1515. ast_debug(1, "SQL query: %s\n", query);
  1516. RES_CONFIG_SQLITE_BEGIN
  1517. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1518. RES_CONFIG_SQLITE_END(error)
  1519. sqlite_freemem(query);
  1520. if (error) {
  1521. /*
  1522. * Unexpected error.
  1523. */
  1524. if (error != SQLITE_ERROR) {
  1525. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1526. sqlite_freemem(errormsg);
  1527. unload_module();
  1528. return 1;
  1529. }
  1530. sqlite_freemem(errormsg);
  1531. errormsg = NULL;
  1532. query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
  1533. if (!query) {
  1534. ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
  1535. unload_module();
  1536. return 1;
  1537. }
  1538. ast_debug(1, "SQL query: %s\n", query);
  1539. RES_CONFIG_SQLITE_BEGIN
  1540. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1541. RES_CONFIG_SQLITE_END(error)
  1542. sqlite_freemem(query);
  1543. if (error) {
  1544. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1545. sqlite_freemem(errormsg);
  1546. unload_module();
  1547. return 1;
  1548. }
  1549. }
  1550. sqlite_freemem(errormsg);
  1551. errormsg = NULL;
  1552. error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
  1553. if (error) {
  1554. unload_module();
  1555. return 1;
  1556. }
  1557. cdr_registered = 1;
  1558. }
  1559. error = ast_cli_register_multiple(cli_status, ARRAY_LEN(cli_status));
  1560. if (error) {
  1561. unload_module();
  1562. return 1;
  1563. }
  1564. cli_status_registered = 1;
  1565. return 0;
  1566. }
  1567. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Realtime SQLite configuration",
  1568. .load = load_module,
  1569. .unload = unload_module,
  1570. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  1571. );