res_config_sqlite.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  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 (asprintf(&sql, sql_table_structure, tablename) < 0) {
  612. ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
  613. sql = NULL;
  614. }
  615. if (!(tblptr = ast_calloc(1, sizeof(*tblptr) + strlen(tablename) + 1))) {
  616. AST_RWLIST_UNLOCK(&sqlite_tables);
  617. ast_log(LOG_ERROR, "Memory error. Cannot cache table '%s'\n", tablename);
  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. return NULL;
  632. }
  633. ast_mutex_unlock(&mutex);
  634. if (AST_LIST_EMPTY(&(tblptr->columns))) {
  635. free_table(tblptr);
  636. AST_RWLIST_UNLOCK(&sqlite_tables);
  637. return NULL;
  638. }
  639. AST_RWLIST_INSERT_TAIL(&sqlite_tables, tblptr, list);
  640. AST_RWLIST_RDLOCK(&(tblptr->columns));
  641. AST_RWLIST_UNLOCK(&sqlite_tables);
  642. return tblptr;
  643. }
  644. #define release_table(a) AST_RWLIST_UNLOCK(&((a)->columns))
  645. static int set_var(char **var, const char *name, const char *value)
  646. {
  647. if (*var)
  648. ast_free(*var);
  649. *var = ast_strdup(value);
  650. if (!*var) {
  651. ast_log(LOG_WARNING, "Unable to allocate variable %s\n", name);
  652. return 1;
  653. }
  654. return 0;
  655. }
  656. static int check_vars(void)
  657. {
  658. if (!dbfile) {
  659. ast_log(LOG_ERROR, "Required parameter undefined: dbfile\n");
  660. return 1;
  661. }
  662. use_cdr = (cdr_table != NULL);
  663. return 0;
  664. }
  665. static int load_config(void)
  666. {
  667. struct ast_config *config;
  668. struct ast_variable *var;
  669. int error;
  670. struct ast_flags config_flags = { 0 };
  671. config = ast_config_load(RES_CONFIG_SQLITE_CONF_FILE, config_flags);
  672. if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
  673. ast_log(LOG_ERROR, "Unable to load " RES_CONFIG_SQLITE_CONF_FILE "\n");
  674. return 1;
  675. }
  676. for (var = ast_variable_browse(config, "general"); var; var = var->next) {
  677. if (!strcasecmp(var->name, "dbfile"))
  678. SET_VAR(config, dbfile, var);
  679. else if (!strcasecmp(var->name, "config_table"))
  680. SET_VAR(config, config_table, var);
  681. else if (!strcasecmp(var->name, "cdr_table")) {
  682. SET_VAR(config, cdr_table, var);
  683. } else
  684. ast_log(LOG_WARNING, "Unknown parameter : %s\n", var->name);
  685. }
  686. ast_config_destroy(config);
  687. error = check_vars();
  688. if (error) {
  689. unload_config();
  690. return 1;
  691. }
  692. return 0;
  693. }
  694. static void unload_config(void)
  695. {
  696. struct sqlite_cache_tables *tbl;
  697. ast_free(dbfile);
  698. dbfile = NULL;
  699. ast_free(config_table);
  700. config_table = NULL;
  701. ast_free(cdr_table);
  702. cdr_table = NULL;
  703. AST_RWLIST_WRLOCK(&sqlite_tables);
  704. while ((tbl = AST_RWLIST_REMOVE_HEAD(&sqlite_tables, list))) {
  705. free_table(tbl);
  706. }
  707. AST_RWLIST_UNLOCK(&sqlite_tables);
  708. }
  709. static int cdr_handler(struct ast_cdr *cdr)
  710. {
  711. char *errormsg = NULL, *tmp, workspace[500];
  712. int error, scannum;
  713. struct sqlite_cache_tables *tbl = find_table(cdr_table);
  714. struct sqlite_cache_columns *col;
  715. struct ast_str *sql1 = ast_str_create(160), *sql2 = ast_str_create(16);
  716. int first = 1;
  717. if (!tbl) {
  718. ast_log(LOG_WARNING, "No such table: %s\n", cdr_table);
  719. return -1;
  720. }
  721. ast_str_set(&sql1, 0, "INSERT INTO %s (", cdr_table);
  722. ast_str_set(&sql2, 0, ") VALUES (");
  723. AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
  724. if (col->isint) {
  725. ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 1);
  726. if (!tmp) {
  727. continue;
  728. }
  729. if (sscanf(tmp, "%30d", &scannum) == 1) {
  730. ast_str_append(&sql1, 0, "%s%s", first ? "" : ",", col->name);
  731. ast_str_append(&sql2, 0, "%s%d", first ? "" : ",", scannum);
  732. }
  733. } else {
  734. ast_cdr_getvar(cdr, col->name, &tmp, workspace, sizeof(workspace), 0, 0);
  735. if (!tmp) {
  736. continue;
  737. }
  738. ast_str_append(&sql1, 0, "%s%s", first ? "" : ",", col->name);
  739. tmp = sqlite_mprintf("%Q", tmp);
  740. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", tmp);
  741. sqlite_freemem(tmp);
  742. }
  743. first = 0;
  744. }
  745. release_table(tbl);
  746. ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
  747. ast_free(sql2);
  748. ast_debug(1, "SQL query: %s\n", ast_str_buffer(sql1));
  749. ast_mutex_lock(&mutex);
  750. RES_CONFIG_SQLITE_BEGIN
  751. error = sqlite_exec(db, ast_str_buffer(sql1), NULL, NULL, &errormsg);
  752. RES_CONFIG_SQLITE_END(error)
  753. ast_mutex_unlock(&mutex);
  754. ast_free(sql1);
  755. if (error) {
  756. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  757. sqlite_freemem(errormsg);
  758. return 1;
  759. }
  760. sqlite_freemem(errormsg);
  761. return 0;
  762. }
  763. static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  764. {
  765. struct cfg_entry_args *args;
  766. struct ast_variable *var;
  767. if (argc != RES_CONFIG_SQLITE_CONFIG_COLUMNS) {
  768. ast_log(LOG_WARNING, "Corrupt table\n");
  769. return 1;
  770. }
  771. args = arg;
  772. if (!strcmp(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], "#include")) {
  773. struct ast_config *cfg;
  774. char *val;
  775. val = argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL];
  776. cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked);
  777. if (!cfg) {
  778. ast_log(LOG_WARNING, "Unable to include %s\n", val);
  779. return 1;
  780. } else {
  781. args->cfg = cfg;
  782. return 0;
  783. }
  784. }
  785. if (!args->cat_name || strcmp(args->cat_name, argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY])) {
  786. args->cat = ast_category_new(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY], "", 99999);
  787. if (!args->cat) {
  788. ast_log(LOG_WARNING, "Unable to allocate category\n");
  789. return 1;
  790. }
  791. ast_free(args->cat_name);
  792. args->cat_name = ast_strdup(argv[RES_CONFIG_SQLITE_CONFIG_CATEGORY]);
  793. if (!args->cat_name) {
  794. ast_category_destroy(args->cat);
  795. return 1;
  796. }
  797. ast_category_append(args->cfg, args->cat);
  798. }
  799. var = ast_variable_new(argv[RES_CONFIG_SQLITE_CONFIG_VAR_NAME], argv[RES_CONFIG_SQLITE_CONFIG_VAR_VAL], "");
  800. if (!var) {
  801. ast_log(LOG_WARNING, "Unable to allocate variable");
  802. return 1;
  803. }
  804. ast_variable_append(args->cat, var);
  805. return 0;
  806. }
  807. static struct ast_config *config_handler(const char *database, const char *table, const char *file,
  808. struct ast_config *cfg, struct ast_flags flags, const char *suggested_incl, const char *who_asked)
  809. {
  810. struct cfg_entry_args args;
  811. char *query, *errormsg = NULL;
  812. int error;
  813. if (!config_table) {
  814. if (!table) {
  815. ast_log(LOG_ERROR, "Table name unspecified\n");
  816. return NULL;
  817. }
  818. } else
  819. table = config_table;
  820. query = sqlite_mprintf(sql_get_config_table, table, file);
  821. if (!query) {
  822. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  823. return NULL;
  824. }
  825. ast_debug(1, "SQL query: %s\n", query);
  826. args.cfg = cfg;
  827. args.cat = NULL;
  828. args.cat_name = NULL;
  829. args.flags = flags;
  830. args.who_asked = who_asked;
  831. ast_mutex_lock(&mutex);
  832. RES_CONFIG_SQLITE_BEGIN
  833. error = sqlite_exec(db, query, add_cfg_entry, &args, &errormsg);
  834. RES_CONFIG_SQLITE_END(error)
  835. ast_mutex_unlock(&mutex);
  836. ast_free(args.cat_name);
  837. sqlite_freemem(query);
  838. if (error) {
  839. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  840. sqlite_freemem(errormsg);
  841. return NULL;
  842. }
  843. sqlite_freemem(errormsg);
  844. return cfg;
  845. }
  846. static size_t get_params(va_list ap, const char ***params_ptr, const char ***vals_ptr, int warn)
  847. {
  848. const char **tmp, *param, *val, **params, **vals;
  849. size_t params_count;
  850. params = NULL;
  851. vals = NULL;
  852. params_count = 0;
  853. while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
  854. if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
  855. ast_free(params);
  856. ast_free(vals);
  857. return 0;
  858. }
  859. params = tmp;
  860. if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
  861. ast_free(params);
  862. ast_free(vals);
  863. return 0;
  864. }
  865. vals = tmp;
  866. params[params_count] = param;
  867. vals[params_count] = val;
  868. params_count++;
  869. }
  870. if (params_count > 0) {
  871. *params_ptr = params;
  872. *vals_ptr = vals;
  873. } else if (warn) {
  874. ast_log(LOG_WARNING, "1 parameter and 1 value at least required\n");
  875. }
  876. return params_count;
  877. }
  878. static int add_rt_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  879. {
  880. struct rt_cfg_entry_args *args;
  881. struct ast_variable *var;
  882. int i;
  883. args = arg;
  884. for (i = 0; i < argc; i++) {
  885. if (!argv[i])
  886. continue;
  887. if (!(var = ast_variable_new(columnNames[i], argv[i], "")))
  888. return 1;
  889. if (!args->var)
  890. args->var = var;
  891. if (!args->last)
  892. args->last = var;
  893. else {
  894. args->last->next = var;
  895. args->last = var;
  896. }
  897. }
  898. return 0;
  899. }
  900. static struct ast_variable * realtime_handler(const char *database, const char *table, va_list ap)
  901. {
  902. char *query, *errormsg = NULL, *op, *tmp_str;
  903. struct rt_cfg_entry_args args;
  904. const char **params, **vals;
  905. size_t params_count;
  906. int error;
  907. if (!table) {
  908. ast_log(LOG_WARNING, "Table name unspecified\n");
  909. return NULL;
  910. }
  911. params_count = get_params(ap, &params, &vals, 1);
  912. if (params_count == 0)
  913. return NULL;
  914. op = (strchr(params[0], ' ') == NULL) ? " =" : "";
  915. /* \cond DOXYGEN_CAN_PARSE_THIS */
  916. #undef QUERY
  917. #define QUERY "SELECT * FROM '%q' WHERE%s %q%s '%q'"
  918. /* \endcond */
  919. query = sqlite_mprintf(QUERY, table, !strcmp(config_table, table) ? " commented = 0 AND" : "", params[0], op, vals[0]);
  920. if (!query) {
  921. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  922. ast_free(params);
  923. ast_free(vals);
  924. return NULL;
  925. }
  926. if (params_count > 1) {
  927. size_t i;
  928. for (i = 1; i < params_count; i++) {
  929. op = (strchr(params[i], ' ') == NULL) ? " =" : "";
  930. tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
  931. sqlite_freemem(query);
  932. if (!tmp_str) {
  933. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  934. ast_free(params);
  935. ast_free(vals);
  936. return NULL;
  937. }
  938. query = tmp_str;
  939. }
  940. }
  941. ast_free(params);
  942. ast_free(vals);
  943. tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
  944. sqlite_freemem(query);
  945. if (!tmp_str) {
  946. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  947. return NULL;
  948. }
  949. query = tmp_str;
  950. ast_debug(1, "SQL query: %s\n", query);
  951. args.var = NULL;
  952. args.last = NULL;
  953. ast_mutex_lock(&mutex);
  954. RES_CONFIG_SQLITE_BEGIN
  955. error = sqlite_exec(db, query, add_rt_cfg_entry, &args, &errormsg);
  956. RES_CONFIG_SQLITE_END(error)
  957. ast_mutex_unlock(&mutex);
  958. sqlite_freemem(query);
  959. if (error) {
  960. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  961. sqlite_freemem(errormsg);
  962. ast_variables_destroy(args.var);
  963. return NULL;
  964. }
  965. sqlite_freemem(errormsg);
  966. return args.var;
  967. }
  968. static int add_rt_multi_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
  969. {
  970. struct rt_multi_cfg_entry_args *args;
  971. struct ast_category *cat;
  972. struct ast_variable *var;
  973. char *cat_name;
  974. size_t i;
  975. args = arg;
  976. cat_name = NULL;
  977. /*
  978. * cat_name should always be set here, since initfield is forged from
  979. * params[0] in realtime_multi_handler(), which is a search parameter
  980. * of the SQL query.
  981. */
  982. for (i = 0; i < argc; i++) {
  983. if (!strcmp(args->initfield, columnNames[i]))
  984. cat_name = argv[i];
  985. }
  986. if (!cat_name) {
  987. ast_log(LOG_ERROR, "Bogus SQL results, cat_name is NULL !\n");
  988. return 1;
  989. }
  990. if (!(cat = ast_category_new(cat_name, "", 99999))) {
  991. ast_log(LOG_WARNING, "Unable to allocate category\n");
  992. return 1;
  993. }
  994. ast_category_append(args->cfg, cat);
  995. for (i = 0; i < argc; i++) {
  996. if (!argv[i] || !strcmp(args->initfield, columnNames[i]))
  997. continue;
  998. if (!(var = ast_variable_new(columnNames[i], argv[i], ""))) {
  999. ast_log(LOG_WARNING, "Unable to allocate variable\n");
  1000. return 1;
  1001. }
  1002. ast_variable_append(cat, var);
  1003. }
  1004. return 0;
  1005. }
  1006. static struct ast_config *realtime_multi_handler(const char *database,
  1007. const char *table, va_list ap)
  1008. {
  1009. char *query, *errormsg = NULL, *op, *tmp_str, *initfield;
  1010. struct rt_multi_cfg_entry_args args;
  1011. const char **params, **vals;
  1012. struct ast_config *cfg;
  1013. size_t params_count;
  1014. int error;
  1015. if (!table) {
  1016. ast_log(LOG_WARNING, "Table name unspecified\n");
  1017. return NULL;
  1018. }
  1019. if (!(cfg = ast_config_new())) {
  1020. ast_log(LOG_WARNING, "Unable to allocate configuration structure\n");
  1021. return NULL;
  1022. }
  1023. if (!(params_count = get_params(ap, &params, &vals, 1))) {
  1024. ast_config_destroy(cfg);
  1025. return NULL;
  1026. }
  1027. if (!(initfield = ast_strdup(params[0]))) {
  1028. ast_config_destroy(cfg);
  1029. ast_free(params);
  1030. ast_free(vals);
  1031. return NULL;
  1032. }
  1033. tmp_str = strchr(initfield, ' ');
  1034. if (tmp_str)
  1035. *tmp_str = '\0';
  1036. op = (!strchr(params[0], ' ')) ? " =" : "";
  1037. /*
  1038. * Asterisk sends us an already escaped string when searching for
  1039. * "exten LIKE" (uh!). Handle it separately.
  1040. */
  1041. tmp_str = (!strcmp(vals[0], "\\_%")) ? "_%" : (char *)vals[0];
  1042. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1043. #undef QUERY
  1044. #define QUERY "SELECT * FROM '%q' WHERE commented = 0 AND %q%s '%q'"
  1045. /* \endcond */
  1046. if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
  1047. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1048. ast_config_destroy(cfg);
  1049. ast_free(params);
  1050. ast_free(vals);
  1051. ast_free(initfield);
  1052. return NULL;
  1053. }
  1054. if (params_count > 1) {
  1055. size_t i;
  1056. for (i = 1; i < params_count; i++) {
  1057. op = (!strchr(params[i], ' ')) ? " =" : "";
  1058. tmp_str = sqlite_mprintf("%s AND %q%s '%q'", query, params[i], op, vals[i]);
  1059. sqlite_freemem(query);
  1060. if (!tmp_str) {
  1061. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1062. ast_config_destroy(cfg);
  1063. ast_free(params);
  1064. ast_free(vals);
  1065. ast_free(initfield);
  1066. return NULL;
  1067. }
  1068. query = tmp_str;
  1069. }
  1070. }
  1071. ast_free(params);
  1072. ast_free(vals);
  1073. if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
  1074. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1075. sqlite_freemem(query);
  1076. ast_config_destroy(cfg);
  1077. ast_free(initfield);
  1078. return NULL;
  1079. }
  1080. sqlite_freemem(query);
  1081. query = tmp_str;
  1082. ast_debug(1, "SQL query: %s\n", query);
  1083. args.cfg = cfg;
  1084. args.initfield = initfield;
  1085. ast_mutex_lock(&mutex);
  1086. RES_CONFIG_SQLITE_BEGIN
  1087. error = sqlite_exec(db, query, add_rt_multi_cfg_entry, &args, &errormsg);
  1088. RES_CONFIG_SQLITE_END(error)
  1089. ast_mutex_unlock(&mutex);
  1090. sqlite_freemem(query);
  1091. ast_free(initfield);
  1092. if (error) {
  1093. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1094. sqlite_freemem(errormsg);
  1095. ast_config_destroy(cfg);
  1096. return NULL;
  1097. }
  1098. sqlite_freemem(errormsg);
  1099. return cfg;
  1100. }
  1101. static int realtime_update_handler(const char *database, const char *table,
  1102. const char *keyfield, const char *entity, va_list ap)
  1103. {
  1104. char *query, *errormsg = NULL, *tmp_str;
  1105. const char **params, **vals;
  1106. size_t params_count;
  1107. int error, rows_num;
  1108. if (!table) {
  1109. ast_log(LOG_WARNING, "Table name unspecified\n");
  1110. return -1;
  1111. }
  1112. if (!(params_count = get_params(ap, &params, &vals, 1)))
  1113. return -1;
  1114. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1115. #undef QUERY
  1116. #define QUERY "UPDATE '%q' SET %q = '%q'"
  1117. /* \endcond */
  1118. if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
  1119. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1120. ast_free(params);
  1121. ast_free(vals);
  1122. return -1;
  1123. }
  1124. if (params_count > 1) {
  1125. size_t i;
  1126. for (i = 1; i < params_count; i++) {
  1127. tmp_str = sqlite_mprintf("%s, %q = '%q'", query, params[i], vals[i]);
  1128. sqlite_freemem(query);
  1129. if (!tmp_str) {
  1130. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1131. ast_free(params);
  1132. ast_free(vals);
  1133. return -1;
  1134. }
  1135. query = tmp_str;
  1136. }
  1137. }
  1138. ast_free(params);
  1139. ast_free(vals);
  1140. if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
  1141. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1142. sqlite_freemem(query);
  1143. return -1;
  1144. }
  1145. sqlite_freemem(query);
  1146. query = tmp_str;
  1147. ast_debug(1, "SQL query: %s\n", query);
  1148. ast_mutex_lock(&mutex);
  1149. RES_CONFIG_SQLITE_BEGIN
  1150. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1151. RES_CONFIG_SQLITE_END(error)
  1152. if (!error)
  1153. rows_num = sqlite_changes(db);
  1154. else
  1155. rows_num = -1;
  1156. ast_mutex_unlock(&mutex);
  1157. sqlite_freemem(query);
  1158. if (error) {
  1159. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1160. }
  1161. sqlite_freemem(errormsg);
  1162. return rows_num;
  1163. }
  1164. static int realtime_update2_handler(const char *database, const char *table,
  1165. va_list ap)
  1166. {
  1167. char *errormsg = NULL, *tmp1, *tmp2;
  1168. int error, rows_num, first = 1;
  1169. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
  1170. struct ast_str *where = ast_str_thread_get(&where_buf, 100);
  1171. const char *param, *value;
  1172. if (!table) {
  1173. ast_log(LOG_WARNING, "Table name unspecified\n");
  1174. return -1;
  1175. }
  1176. if (!sql) {
  1177. return -1;
  1178. }
  1179. ast_str_set(&sql, 0, "UPDATE %s SET", table);
  1180. ast_str_set(&where, 0, " WHERE");
  1181. while ((param = va_arg(ap, const char *))) {
  1182. value = va_arg(ap, const char *);
  1183. ast_str_append(&where, 0, "%s %s = %s",
  1184. first ? "" : " AND",
  1185. tmp1 = sqlite_mprintf("%q", param),
  1186. tmp2 = sqlite_mprintf("%Q", value));
  1187. sqlite_freemem(tmp1);
  1188. sqlite_freemem(tmp2);
  1189. first = 0;
  1190. }
  1191. if (first) {
  1192. ast_log(LOG_ERROR, "No criteria specified on update to '%s@%s'!\n", table, database);
  1193. return -1;
  1194. }
  1195. first = 1;
  1196. while ((param = va_arg(ap, const char *))) {
  1197. value = va_arg(ap, const char *);
  1198. ast_str_append(&sql, 0, "%s %s = %s",
  1199. first ? "" : ",",
  1200. tmp1 = sqlite_mprintf("%q", param),
  1201. tmp2 = sqlite_mprintf("%Q", value));
  1202. sqlite_freemem(tmp1);
  1203. sqlite_freemem(tmp2);
  1204. first = 0;
  1205. }
  1206. ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
  1207. ast_debug(1, "SQL query: %s\n", ast_str_buffer(sql));
  1208. ast_mutex_lock(&mutex);
  1209. RES_CONFIG_SQLITE_BEGIN
  1210. error = sqlite_exec(db, ast_str_buffer(sql), NULL, NULL, &errormsg);
  1211. RES_CONFIG_SQLITE_END(error)
  1212. if (!error) {
  1213. rows_num = sqlite_changes(db);
  1214. } else {
  1215. rows_num = -1;
  1216. }
  1217. ast_mutex_unlock(&mutex);
  1218. if (error) {
  1219. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1220. }
  1221. sqlite_freemem(errormsg);
  1222. return rows_num;
  1223. }
  1224. static int realtime_store_handler(const char *database, const char *table, va_list ap)
  1225. {
  1226. char *errormsg = NULL, *tmp_str, *tmp_keys = NULL, *tmp_keys2 = NULL, *tmp_vals = NULL, *tmp_vals2 = NULL;
  1227. const char **params, **vals;
  1228. size_t params_count;
  1229. int error, rows_id;
  1230. size_t i;
  1231. if (!table) {
  1232. ast_log(LOG_WARNING, "Table name unspecified\n");
  1233. return -1;
  1234. }
  1235. if (!(params_count = get_params(ap, &params, &vals, 1)))
  1236. return -1;
  1237. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1238. #undef QUERY
  1239. #define QUERY "INSERT into '%q' (%s) VALUES (%s);"
  1240. /* \endcond */
  1241. for (i = 0; i < params_count; i++) {
  1242. if ( tmp_keys2 ) {
  1243. tmp_keys = sqlite_mprintf("%s, %q", tmp_keys2, params[i]);
  1244. sqlite_freemem(tmp_keys2);
  1245. } else {
  1246. tmp_keys = sqlite_mprintf("%q", params[i]);
  1247. }
  1248. if (!tmp_keys) {
  1249. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1250. sqlite_freemem(tmp_vals);
  1251. ast_free(params);
  1252. ast_free(vals);
  1253. return -1;
  1254. }
  1255. if ( tmp_vals2 ) {
  1256. tmp_vals = sqlite_mprintf("%s, '%q'", tmp_vals2, vals[i]);
  1257. sqlite_freemem(tmp_vals2);
  1258. } else {
  1259. tmp_vals = sqlite_mprintf("'%q'", vals[i]);
  1260. }
  1261. if (!tmp_vals) {
  1262. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1263. sqlite_freemem(tmp_keys);
  1264. ast_free(params);
  1265. ast_free(vals);
  1266. return -1;
  1267. }
  1268. tmp_keys2 = tmp_keys;
  1269. tmp_vals2 = tmp_vals;
  1270. }
  1271. ast_free(params);
  1272. ast_free(vals);
  1273. if (!(tmp_str = sqlite_mprintf(QUERY, table, tmp_keys, tmp_vals))) {
  1274. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1275. sqlite_freemem(tmp_keys);
  1276. sqlite_freemem(tmp_vals);
  1277. return -1;
  1278. }
  1279. sqlite_freemem(tmp_keys);
  1280. sqlite_freemem(tmp_vals);
  1281. ast_debug(1, "SQL query: %s\n", tmp_str);
  1282. ast_mutex_lock(&mutex);
  1283. RES_CONFIG_SQLITE_BEGIN
  1284. error = sqlite_exec(db, tmp_str, NULL, NULL, &errormsg);
  1285. RES_CONFIG_SQLITE_END(error)
  1286. if (!error) {
  1287. rows_id = sqlite_last_insert_rowid(db);
  1288. } else {
  1289. rows_id = -1;
  1290. }
  1291. ast_mutex_unlock(&mutex);
  1292. sqlite_freemem(tmp_str);
  1293. if (error) {
  1294. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1295. }
  1296. sqlite_freemem(errormsg);
  1297. return rows_id;
  1298. }
  1299. static int realtime_destroy_handler(const char *database, const char *table,
  1300. const char *keyfield, const char *entity, va_list ap)
  1301. {
  1302. char *query, *errormsg = NULL, *tmp_str;
  1303. const char **params = NULL, **vals = NULL;
  1304. size_t params_count;
  1305. int error, rows_num;
  1306. size_t i;
  1307. if (!table) {
  1308. ast_log(LOG_WARNING, "Table name unspecified\n");
  1309. return -1;
  1310. }
  1311. params_count = get_params(ap, &params, &vals, 0);
  1312. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1313. #undef QUERY
  1314. #define QUERY "DELETE FROM '%q' WHERE"
  1315. /* \endcond */
  1316. if (!(query = sqlite_mprintf(QUERY, table))) {
  1317. ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
  1318. ast_free(params);
  1319. ast_free(vals);
  1320. return -1;
  1321. }
  1322. for (i = 0; i < params_count; i++) {
  1323. tmp_str = sqlite_mprintf("%s %q = '%q' AND", query, params[i], vals[i]);
  1324. sqlite_freemem(query);
  1325. if (!tmp_str) {
  1326. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1327. ast_free(params);
  1328. ast_free(vals);
  1329. return -1;
  1330. }
  1331. query = tmp_str;
  1332. }
  1333. ast_free(params);
  1334. ast_free(vals);
  1335. if (!(tmp_str = sqlite_mprintf("%s %q = '%q';", query, keyfield, entity))) {
  1336. ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
  1337. sqlite_freemem(query);
  1338. return -1;
  1339. }
  1340. sqlite_freemem(query);
  1341. query = tmp_str;
  1342. ast_debug(1, "SQL query: %s\n", query);
  1343. ast_mutex_lock(&mutex);
  1344. RES_CONFIG_SQLITE_BEGIN
  1345. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1346. RES_CONFIG_SQLITE_END(error)
  1347. if (!error) {
  1348. rows_num = sqlite_changes(db);
  1349. } else {
  1350. rows_num = -1;
  1351. }
  1352. ast_mutex_unlock(&mutex);
  1353. sqlite_freemem(query);
  1354. if (error) {
  1355. ast_log(LOG_WARNING, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1356. }
  1357. sqlite_freemem(errormsg);
  1358. return rows_num;
  1359. }
  1360. static int realtime_require_handler(const char *unused, const char *tablename, va_list ap)
  1361. {
  1362. struct sqlite_cache_tables *tbl = find_table(tablename);
  1363. struct sqlite_cache_columns *col;
  1364. char *elm;
  1365. int type, res = 0;
  1366. if (!tbl) {
  1367. return -1;
  1368. }
  1369. while ((elm = va_arg(ap, char *))) {
  1370. type = va_arg(ap, require_type);
  1371. va_arg(ap, int);
  1372. /* Check if the field matches the criteria */
  1373. AST_RWLIST_TRAVERSE(&tbl->columns, col, list) {
  1374. if (strcmp(col->name, elm) == 0) {
  1375. /* SQLite only has two types - the 32-bit integer field that
  1376. * is the key column, and everything else (everything else
  1377. * being a string).
  1378. */
  1379. if (col->isint && !ast_rq_is_int(type)) {
  1380. ast_log(LOG_WARNING, "Realtime table %s: column '%s' is an integer field, but Asterisk requires that it not be!\n", tablename, col->name);
  1381. res = -1;
  1382. }
  1383. break;
  1384. }
  1385. }
  1386. if (!col) {
  1387. ast_log(LOG_WARNING, "Realtime table %s requires column '%s', but that column does not exist!\n", tablename, elm);
  1388. }
  1389. }
  1390. AST_RWLIST_UNLOCK(&(tbl->columns));
  1391. return res;
  1392. }
  1393. static int realtime_unload_handler(const char *unused, const char *tablename)
  1394. {
  1395. struct sqlite_cache_tables *tbl;
  1396. AST_RWLIST_WRLOCK(&sqlite_tables);
  1397. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sqlite_tables, tbl, list) {
  1398. if (!strcasecmp(tbl->name, tablename)) {
  1399. AST_RWLIST_REMOVE_CURRENT(list);
  1400. free_table(tbl);
  1401. }
  1402. }
  1403. AST_RWLIST_TRAVERSE_SAFE_END
  1404. AST_RWLIST_UNLOCK(&sqlite_tables);
  1405. return 0;
  1406. }
  1407. static char *handle_cli_show_sqlite_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1408. {
  1409. switch (cmd) {
  1410. case CLI_INIT:
  1411. e->command = "sqlite show status";
  1412. e->usage =
  1413. "Usage: sqlite show status\n"
  1414. " Show status information about the SQLite 2 driver\n";
  1415. return NULL;
  1416. case CLI_GENERATE:
  1417. return NULL;
  1418. }
  1419. if (a->argc != 3)
  1420. return CLI_SHOWUSAGE;
  1421. ast_cli(a->fd, "SQLite database path: %s\n", dbfile);
  1422. ast_cli(a->fd, "config_table: ");
  1423. if (!config_table)
  1424. ast_cli(a->fd, "unspecified, must be present in extconfig.conf\n");
  1425. else
  1426. ast_cli(a->fd, "%s\n", config_table);
  1427. ast_cli(a->fd, "cdr_table: ");
  1428. if (!cdr_table)
  1429. ast_cli(a->fd, "unspecified, CDR support disabled\n");
  1430. else
  1431. ast_cli(a->fd, "%s\n", cdr_table);
  1432. return CLI_SUCCESS;
  1433. }
  1434. static char *handle_cli_sqlite_show_tables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1435. {
  1436. struct sqlite_cache_tables *tbl;
  1437. struct sqlite_cache_columns *col;
  1438. int found = 0;
  1439. switch (cmd) {
  1440. case CLI_INIT:
  1441. e->command = "sqlite show tables";
  1442. e->usage =
  1443. "Usage: sqlite show tables\n"
  1444. " Show table information about the SQLite 2 driver\n";
  1445. return NULL;
  1446. case CLI_GENERATE:
  1447. return NULL;
  1448. }
  1449. if (a->argc != 3)
  1450. return CLI_SHOWUSAGE;
  1451. AST_RWLIST_RDLOCK(&sqlite_tables);
  1452. AST_RWLIST_TRAVERSE(&sqlite_tables, tbl, list) {
  1453. found++;
  1454. ast_cli(a->fd, "Table %s:\n", tbl->name);
  1455. AST_RWLIST_TRAVERSE(&(tbl->columns), col, list) {
  1456. fprintf(stderr, "%s\n", col->name);
  1457. ast_cli(a->fd, " %20.20s %-30.30s\n", col->name, col->type);
  1458. }
  1459. }
  1460. AST_RWLIST_UNLOCK(&sqlite_tables);
  1461. if (!found) {
  1462. ast_cli(a->fd, "No tables currently in cache\n");
  1463. }
  1464. return CLI_SUCCESS;
  1465. }
  1466. static int unload_module(void)
  1467. {
  1468. if (cli_status_registered)
  1469. ast_cli_unregister_multiple(cli_status, ARRAY_LEN(cli_status));
  1470. if (cdr_registered)
  1471. ast_cdr_unregister(RES_CONFIG_SQLITE_NAME);
  1472. ast_config_engine_deregister(&sqlite_engine);
  1473. if (db)
  1474. sqlite_close(db);
  1475. unload_config();
  1476. return 0;
  1477. }
  1478. static int load_module(void)
  1479. {
  1480. char *errormsg = NULL;
  1481. int error;
  1482. db = NULL;
  1483. cdr_registered = 0;
  1484. cli_status_registered = 0;
  1485. dbfile = NULL;
  1486. config_table = NULL;
  1487. cdr_table = NULL;
  1488. error = load_config();
  1489. if (error)
  1490. return AST_MODULE_LOAD_DECLINE;
  1491. if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
  1492. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1493. sqlite_freemem(errormsg);
  1494. unload_module();
  1495. return 1;
  1496. }
  1497. sqlite_freemem(errormsg);
  1498. errormsg = NULL;
  1499. ast_config_engine_register(&sqlite_engine);
  1500. if (use_cdr) {
  1501. char *query;
  1502. /* \cond DOXYGEN_CAN_PARSE_THIS */
  1503. #undef QUERY
  1504. #define QUERY "SELECT COUNT(id) FROM %Q;"
  1505. /* \endcond */
  1506. query = sqlite_mprintf(QUERY, cdr_table);
  1507. if (!query) {
  1508. ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
  1509. unload_module();
  1510. return 1;
  1511. }
  1512. ast_debug(1, "SQL query: %s\n", query);
  1513. RES_CONFIG_SQLITE_BEGIN
  1514. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1515. RES_CONFIG_SQLITE_END(error)
  1516. sqlite_freemem(query);
  1517. if (error) {
  1518. /*
  1519. * Unexpected error.
  1520. */
  1521. if (error != SQLITE_ERROR) {
  1522. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1523. sqlite_freemem(errormsg);
  1524. unload_module();
  1525. return 1;
  1526. }
  1527. sqlite_freemem(errormsg);
  1528. errormsg = NULL;
  1529. query = sqlite_mprintf(sql_create_cdr_table, cdr_table);
  1530. if (!query) {
  1531. ast_log(LOG_ERROR, "Unable to allocate SQL query\n");
  1532. unload_module();
  1533. return 1;
  1534. }
  1535. ast_debug(1, "SQL query: %s\n", query);
  1536. RES_CONFIG_SQLITE_BEGIN
  1537. error = sqlite_exec(db, query, NULL, NULL, &errormsg);
  1538. RES_CONFIG_SQLITE_END(error)
  1539. sqlite_freemem(query);
  1540. if (error) {
  1541. ast_log(LOG_ERROR, "%s\n", S_OR(errormsg, sqlite_error_string(error)));
  1542. sqlite_freemem(errormsg);
  1543. unload_module();
  1544. return 1;
  1545. }
  1546. }
  1547. sqlite_freemem(errormsg);
  1548. errormsg = NULL;
  1549. error = ast_cdr_register(RES_CONFIG_SQLITE_NAME, RES_CONFIG_SQLITE_DESCRIPTION, cdr_handler);
  1550. if (error) {
  1551. unload_module();
  1552. return 1;
  1553. }
  1554. cdr_registered = 1;
  1555. }
  1556. error = ast_cli_register_multiple(cli_status, ARRAY_LEN(cli_status));
  1557. if (error) {
  1558. unload_module();
  1559. return 1;
  1560. }
  1561. cli_status_registered = 1;
  1562. return 0;
  1563. }
  1564. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Realtime SQLite configuration",
  1565. .load = load_module,
  1566. .unload = unload_module,
  1567. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  1568. );