res_config_sqlite.c 46 KB

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