res_config_sqlite.c 46 KB

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