res_config_mysql.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999-2005, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com> - Asterisk Author
  7. * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
  8. *
  9. * See http://www.asterisk.org for more information about
  10. * the Asterisk project. Please do not directly contact
  11. * any of the maintainers of this project for assistance;
  12. * the project provides a web site, mailing lists and IRC
  13. * channels for your use.
  14. *
  15. * This program is free software, distributed under the terms of
  16. * the GNU General Public License Version 2. See the LICENSE file
  17. * at the top of the source tree.
  18. */
  19. /*!
  20. * \file
  21. * \brief MySQL CDR backend
  22. */
  23. /*** MODULEINFO
  24. <depend>mysqlclient</depend>
  25. <defaultenabled>no</defaultenabled>
  26. <support_level>extended</support_level>
  27. ***/
  28. #include "asterisk.h"
  29. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  30. #include <sys/stat.h>
  31. #include <mysql/mysql.h>
  32. #include <mysql/mysql_version.h>
  33. #include <mysql/errmsg.h>
  34. #include "asterisk/channel.h"
  35. #include "asterisk/logger.h"
  36. #include "asterisk/config.h"
  37. #include "asterisk/module.h"
  38. #include "asterisk/lock.h"
  39. #include "asterisk/options.h"
  40. #include "asterisk/cli.h"
  41. #include "asterisk/utils.h"
  42. #include "asterisk/threadstorage.h"
  43. #include "asterisk/strings.h"
  44. #define RES_CONFIG_MYSQL_CONF "res_config_mysql.conf"
  45. #define RES_CONFIG_MYSQL_CONF_OLD "res_mysql.conf"
  46. #define READHANDLE 0
  47. #define WRITEHANDLE 1
  48. #define ESCAPE_STRING(buf, var) \
  49. do { \
  50. struct ast_str *semi = ast_str_thread_get(&scratch2_buf, strlen(var) * 3 + 1); \
  51. const char *chunk = var; \
  52. ast_str_reset(semi); \
  53. for (; *chunk; chunk++) { \
  54. if (strchr(";^", *chunk)) { \
  55. ast_str_append(&semi, 0, "^%02hhX", *chunk); \
  56. } else { \
  57. ast_str_append(&semi, 0, "%c", *chunk); \
  58. } \
  59. } \
  60. if (ast_str_strlen(semi) * 2 + 1 > ast_str_size(buf)) { \
  61. ast_str_make_space(&(buf), ast_str_strlen(semi) * 2 + 1); \
  62. } \
  63. mysql_real_escape_string(&dbh->handle, ast_str_buffer(buf), ast_str_buffer(semi), ast_str_strlen(semi)); \
  64. } while (0)
  65. AST_THREADSTORAGE(sql_buf);
  66. AST_THREADSTORAGE(sql2_buf);
  67. AST_THREADSTORAGE(find_buf);
  68. AST_THREADSTORAGE(scratch_buf);
  69. AST_THREADSTORAGE(scratch2_buf);
  70. AST_THREADSTORAGE(modify_buf);
  71. AST_THREADSTORAGE(modify2_buf);
  72. AST_THREADSTORAGE(modify3_buf);
  73. enum requirements { RQ_WARN, RQ_CREATECLOSE, RQ_CREATECHAR };
  74. struct mysql_conn {
  75. AST_RWLIST_ENTRY(mysql_conn) list;
  76. ast_mutex_t lock;
  77. MYSQL handle;
  78. char host[50];
  79. char name[50];
  80. char user[50];
  81. char pass[50];
  82. char sock[50];
  83. char charset[50];
  84. int port;
  85. int connected;
  86. time_t connect_time;
  87. enum requirements requirements;
  88. char unique_name[0];
  89. };
  90. struct columns {
  91. char *name;
  92. char *type;
  93. char *dflt;
  94. char null;
  95. int len;
  96. AST_LIST_ENTRY(columns) list;
  97. };
  98. struct tables {
  99. ast_mutex_t lock;
  100. AST_LIST_HEAD_NOLOCK(mysql_columns, columns) columns;
  101. AST_LIST_ENTRY(tables) list;
  102. struct mysql_conn *database;
  103. char name[0];
  104. };
  105. static AST_LIST_HEAD_STATIC(mysql_tables, tables);
  106. static AST_RWLIST_HEAD_STATIC(databases, mysql_conn);
  107. static int parse_config(int reload);
  108. static int mysql_reconnect(struct mysql_conn *conn);
  109. static char *handle_cli_realtime_mysql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  110. static char *handle_cli_realtime_mysql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  111. static int load_mysql_config(struct ast_config *config, const char *category, struct mysql_conn *conn);
  112. static int require_mysql(const char *database, const char *tablename, va_list ap);
  113. static int internal_require(const char *database, const char *table, ...) attribute_sentinel;
  114. static struct ast_cli_entry cli_realtime_mysql_status[] = {
  115. AST_CLI_DEFINE(handle_cli_realtime_mysql_status, "Shows connection information for the MySQL RealTime driver"),
  116. AST_CLI_DEFINE(handle_cli_realtime_mysql_cache, "Shows cached tables within the MySQL realtime driver"),
  117. };
  118. static struct mysql_conn *find_database(const char *database, int for_write)
  119. {
  120. char *whichdb;
  121. const char *ptr;
  122. struct mysql_conn *cur;
  123. if ((ptr = strchr(database, '/'))) {
  124. /* Multiple databases encoded within string */
  125. if (for_write) {
  126. whichdb = ast_strdupa(ptr + 1);
  127. } else {
  128. whichdb = alloca(ptr - database + 1);
  129. strncpy(whichdb, database, ptr - database);
  130. whichdb[ptr - database] = '\0';
  131. }
  132. } else {
  133. whichdb = ast_strdupa(database);
  134. }
  135. AST_RWLIST_RDLOCK(&databases);
  136. AST_RWLIST_TRAVERSE(&databases, cur, list) {
  137. if (!strcmp(cur->unique_name, whichdb)) {
  138. ast_mutex_lock(&cur->lock);
  139. break;
  140. }
  141. }
  142. AST_RWLIST_UNLOCK(&databases);
  143. return cur;
  144. }
  145. #define release_database(a) ast_mutex_unlock(&(a)->lock)
  146. static int internal_require(const char *database, const char *table, ...)
  147. {
  148. va_list ap;
  149. int res;
  150. va_start(ap, table);
  151. res = require_mysql(database, table, ap);
  152. va_end(ap);
  153. return res;
  154. }
  155. static void destroy_table(struct tables *table)
  156. {
  157. struct columns *column;
  158. ast_mutex_lock(&table->lock);
  159. while ((column = AST_LIST_REMOVE_HEAD(&table->columns, list))) {
  160. ast_free(column);
  161. }
  162. ast_mutex_unlock(&table->lock);
  163. ast_mutex_destroy(&table->lock);
  164. ast_free(table);
  165. }
  166. static struct tables *find_table(const char *database, const char *tablename)
  167. {
  168. struct columns *column;
  169. struct tables *table;
  170. struct ast_str *sql = ast_str_thread_get(&find_buf, 30);
  171. char *fname, *ftype, *flen, *fdflt, *fnull;
  172. struct mysql_conn *dbh;
  173. MYSQL_RES *result;
  174. MYSQL_ROW row;
  175. if (!(dbh = find_database(database, 1))) {
  176. return NULL;
  177. }
  178. AST_LIST_LOCK(&mysql_tables);
  179. AST_LIST_TRAVERSE(&mysql_tables, table, list) {
  180. if (!strcasecmp(table->name, tablename)) {
  181. ast_mutex_lock(&table->lock);
  182. AST_LIST_UNLOCK(&mysql_tables);
  183. release_database(dbh);
  184. return table;
  185. }
  186. }
  187. /* Not found, scan the table */
  188. ast_str_set(&sql, 0, "DESC %s", tablename);
  189. if (!mysql_reconnect(dbh)) {
  190. release_database(dbh);
  191. AST_LIST_UNLOCK(&mysql_tables);
  192. return NULL;
  193. }
  194. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  195. ast_log(LOG_ERROR, "Failed to query database '%s', table '%s' columns: %s\n", database, tablename, mysql_error(&dbh->handle));
  196. release_database(dbh);
  197. AST_LIST_UNLOCK(&mysql_tables);
  198. return NULL;
  199. }
  200. if (!(table = ast_calloc(1, sizeof(*table) + strlen(tablename) + 1))) {
  201. ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
  202. release_database(dbh);
  203. AST_LIST_UNLOCK(&mysql_tables);
  204. return NULL;
  205. }
  206. strcpy(table->name, tablename); /* SAFE */
  207. table->database = dbh;
  208. ast_mutex_init(&table->lock);
  209. AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
  210. if ((result = mysql_store_result(&dbh->handle))) {
  211. while ((row = mysql_fetch_row(result))) {
  212. fname = row[0];
  213. ftype = row[1];
  214. fnull = row[2];
  215. fdflt = row[4];
  216. ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
  217. if (fdflt == NULL) {
  218. fdflt = "";
  219. }
  220. if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + strlen(fdflt) + 3))) {
  221. ast_log(LOG_ERROR, "Unable to allocate column element %s for %s\n", fname, tablename);
  222. destroy_table(table);
  223. release_database(dbh);
  224. AST_LIST_UNLOCK(&mysql_tables);
  225. return NULL;
  226. }
  227. if ((flen = strchr(ftype, '('))) {
  228. sscanf(flen, "(%30d)", &column->len);
  229. } else {
  230. /* Columns like dates, times, and timestamps don't have a length */
  231. column->len = -1;
  232. }
  233. column->name = (char *)column + sizeof(*column);
  234. column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
  235. column->dflt = (char *)column + sizeof(*column) + strlen(fname) + 1 + strlen(ftype) + 1;
  236. strcpy(column->name, fname);
  237. strcpy(column->type, ftype);
  238. strcpy(column->dflt, fdflt);
  239. column->null = (strcmp(fnull, "YES") == 0 ? 1 : 0);
  240. AST_LIST_INSERT_TAIL(&table->columns, column, list);
  241. }
  242. mysql_free_result(result);
  243. }
  244. AST_LIST_INSERT_TAIL(&mysql_tables, table, list);
  245. ast_mutex_lock(&table->lock);
  246. AST_LIST_UNLOCK(&mysql_tables);
  247. release_database(dbh);
  248. return table;
  249. }
  250. static void release_table(struct tables *table)
  251. {
  252. if (table) {
  253. ast_mutex_unlock(&table->lock);
  254. }
  255. }
  256. static struct columns *find_column(struct tables *table, const char *colname)
  257. {
  258. struct columns *column;
  259. AST_LIST_TRAVERSE(&table->columns, column, list) {
  260. if (strcmp(column->name, colname) == 0) {
  261. break;
  262. }
  263. }
  264. return column;
  265. }
  266. static char *decode_chunk(char *chunk)
  267. {
  268. char *orig = chunk;
  269. for (; *chunk; chunk++) {
  270. if (*chunk == '^' && strchr("0123456789ABCDEFabcdef", chunk[1]) && strchr("0123456789ABCDEFabcdef", chunk[2])) {
  271. sscanf(chunk + 1, "%02hhX", chunk);
  272. memmove(chunk + 1, chunk + 3, strlen(chunk + 3) + 1);
  273. }
  274. }
  275. return orig;
  276. }
  277. static struct ast_variable *realtime_mysql(const char *database, const char *table, va_list ap)
  278. {
  279. struct mysql_conn *dbh;
  280. MYSQL_RES *result;
  281. MYSQL_ROW row;
  282. MYSQL_FIELD *fields;
  283. int numFields, i;
  284. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  285. struct ast_str *buf = ast_str_thread_get(&scratch_buf, 16);
  286. char *stringp;
  287. char *chunk;
  288. char *op;
  289. const char *newparam, *newval;
  290. struct ast_variable *var=NULL, *prev=NULL;
  291. if (!(dbh = find_database(database, 0))) {
  292. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: %s (check res_mysql.conf)\n", database);
  293. return NULL;
  294. }
  295. if (!table) {
  296. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  297. release_database(dbh);
  298. return NULL;
  299. }
  300. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  301. newparam = va_arg(ap, const char *);
  302. newval = va_arg(ap, const char *);
  303. if (!newparam || !newval) {
  304. ast_log(LOG_WARNING, "MySQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
  305. release_database(dbh);
  306. return NULL;
  307. }
  308. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  309. if (!mysql_reconnect(dbh)) {
  310. release_database(dbh);
  311. return NULL;
  312. }
  313. /* Create the first part of the query using the first parameter/value pairs we just extracted
  314. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  315. if (!strchr(newparam, ' '))
  316. op = " =";
  317. else
  318. op = "";
  319. ESCAPE_STRING(buf, newval);
  320. ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, ast_str_buffer(buf));
  321. while ((newparam = va_arg(ap, const char *))) {
  322. newval = va_arg(ap, const char *);
  323. if (!strchr(newparam, ' '))
  324. op = " =";
  325. else
  326. op = "";
  327. ESCAPE_STRING(buf, newval);
  328. ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(buf));
  329. }
  330. va_end(ap);
  331. ast_debug(1, "MySQL RealTime: Retrieve SQL: %s\n", ast_str_buffer(sql));
  332. /* Execution. */
  333. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  334. ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database: %s\n", mysql_error(&dbh->handle));
  335. release_database(dbh);
  336. return NULL;
  337. }
  338. if ((result = mysql_store_result(&dbh->handle))) {
  339. numFields = mysql_num_fields(result);
  340. fields = mysql_fetch_fields(result);
  341. while ((row = mysql_fetch_row(result))) {
  342. for (i = 0; i < numFields; i++) {
  343. /* Encode NULL values separately from blank values, for the Realtime API */
  344. if (row[i] == NULL) {
  345. row[i] = "";
  346. } else if (ast_strlen_zero(row[i])) {
  347. row[i] = " ";
  348. }
  349. for (stringp = row[i], chunk = strsep(&stringp, ";"); chunk; chunk = strsep(&stringp, ";")) {
  350. if (prev) {
  351. if ((prev->next = ast_variable_new(fields[i].name, decode_chunk(chunk), ""))) {
  352. prev = prev->next;
  353. }
  354. } else {
  355. prev = var = ast_variable_new(fields[i].name, decode_chunk(chunk), "");
  356. }
  357. }
  358. }
  359. }
  360. } else {
  361. ast_debug(1, "MySQL RealTime: Could not find any rows in table %s.\n", table);
  362. }
  363. release_database(dbh);
  364. mysql_free_result(result);
  365. return var;
  366. }
  367. static struct ast_config *realtime_multi_mysql(const char *database, const char *table, va_list ap)
  368. {
  369. struct mysql_conn *dbh;
  370. MYSQL_RES *result;
  371. MYSQL_ROW row;
  372. MYSQL_FIELD *fields;
  373. int numFields, i;
  374. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  375. struct ast_str *buf = ast_str_thread_get(&scratch_buf, 16);
  376. const char *initfield = NULL;
  377. char *stringp;
  378. char *chunk;
  379. char *op;
  380. const char *newparam, *newval;
  381. struct ast_variable *var = NULL;
  382. struct ast_config *cfg = NULL;
  383. struct ast_category *cat = NULL;
  384. if (!(dbh = find_database(database, 0))) {
  385. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: '%s' (check res_mysql.conf)\n", database);
  386. return NULL;
  387. }
  388. if (!table) {
  389. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  390. release_database(dbh);
  391. return NULL;
  392. }
  393. if (!(cfg = ast_config_new())) {
  394. /* If I can't alloc memory at this point, why bother doing anything else? */
  395. ast_log(LOG_WARNING, "Out of memory!\n");
  396. release_database(dbh);
  397. return NULL;
  398. }
  399. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  400. newparam = va_arg(ap, const char *);
  401. newval = va_arg(ap, const char *);
  402. if (!newparam || !newval) {
  403. ast_log(LOG_WARNING, "MySQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
  404. ast_config_destroy(cfg);
  405. release_database(dbh);
  406. return NULL;
  407. }
  408. initfield = ast_strdupa(newparam);
  409. if (initfield && (op = strchr(initfield, ' '))) {
  410. *op = '\0';
  411. }
  412. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  413. if (!mysql_reconnect(dbh)) {
  414. release_database(dbh);
  415. ast_config_destroy(cfg);
  416. return NULL;
  417. }
  418. /* Create the first part of the query using the first parameter/value pairs we just extracted
  419. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  420. if (!strchr(newparam, ' '))
  421. op = " =";
  422. else
  423. op = "";
  424. ESCAPE_STRING(buf, newval);
  425. ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, ast_str_buffer(buf));
  426. while ((newparam = va_arg(ap, const char *))) {
  427. newval = va_arg(ap, const char *);
  428. if (!strchr(newparam, ' ')) op = " ="; else op = "";
  429. ESCAPE_STRING(buf, newval);
  430. ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(buf));
  431. }
  432. if (initfield) {
  433. ast_str_append(&sql, 0, " ORDER BY %s", initfield);
  434. }
  435. va_end(ap);
  436. ast_debug(1, "MySQL RealTime: Retrieve SQL: %s\n", ast_str_buffer(sql));
  437. /* Execution. */
  438. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  439. ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database: %s\n", mysql_error(&dbh->handle));
  440. release_database(dbh);
  441. ast_config_destroy(cfg);
  442. return NULL;
  443. }
  444. if ((result = mysql_store_result(&dbh->handle))) {
  445. numFields = mysql_num_fields(result);
  446. fields = mysql_fetch_fields(result);
  447. while ((row = mysql_fetch_row(result))) {
  448. var = NULL;
  449. cat = ast_category_new("", "", -1);
  450. if (!cat) {
  451. ast_log(LOG_WARNING, "Out of memory!\n");
  452. continue;
  453. }
  454. for (i = 0; i < numFields; i++) {
  455. if (ast_strlen_zero(row[i]))
  456. continue;
  457. for (stringp = row[i], chunk = strsep(&stringp, ";"); chunk; chunk = strsep(&stringp, ";")) {
  458. if (chunk && !ast_strlen_zero(decode_chunk(ast_strip(chunk)))) {
  459. if (initfield && !strcmp(initfield, fields[i].name)) {
  460. ast_category_rename(cat, chunk);
  461. }
  462. var = ast_variable_new(fields[i].name, chunk, "");
  463. ast_variable_append(cat, var);
  464. }
  465. }
  466. }
  467. ast_category_append(cfg, cat);
  468. }
  469. } else {
  470. ast_debug(1, "MySQL RealTime: Could not find any rows in table %s.\n", table);
  471. }
  472. release_database(dbh);
  473. mysql_free_result(result);
  474. return cfg;
  475. }
  476. static int update_mysql(const char *database, const char *tablename, const char *keyfield, const char *lookup, va_list ap)
  477. {
  478. struct mysql_conn *dbh;
  479. my_ulonglong numrows;
  480. const char *newparam, *newval;
  481. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100), *buf = ast_str_thread_get(&scratch_buf, 100);
  482. struct tables *table;
  483. struct columns *column = NULL;
  484. if (!(dbh = find_database(database, 1))) {
  485. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: '%s' (check res_mysql.conf)\n", database);
  486. return -1;
  487. }
  488. if (!tablename) {
  489. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  490. release_database(dbh);
  491. return -1;
  492. }
  493. if (!(table = find_table(database, tablename))) {
  494. ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
  495. release_database(dbh);
  496. return -1;
  497. }
  498. if (!(column = find_column(table, keyfield))) {
  499. ast_log(LOG_ERROR, "MySQL RealTime: Updating on column '%s', but that column does not exist within the table '%s' (db '%s')!\n", keyfield, tablename, database);
  500. release_table(table);
  501. release_database(dbh);
  502. return -1;
  503. }
  504. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  505. newparam = va_arg(ap, const char *);
  506. newval = va_arg(ap, const char *);
  507. if (!newparam || !newval) {
  508. ast_log(LOG_WARNING, "MySQL RealTime: Realtime update requires at least 1 parameter and 1 value to update.\n");
  509. release_table(table);
  510. release_database(dbh);
  511. return -1;
  512. }
  513. /* Check that the column exists in the table */
  514. if (!(column = find_column(table, newparam))) {
  515. ast_log(LOG_ERROR, "MySQL RealTime: Updating column '%s', but that column does not exist within the table '%s' (first pair MUST exist)!\n", newparam, tablename);
  516. release_table(table);
  517. release_database(dbh);
  518. return -1;
  519. }
  520. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  521. if (!mysql_reconnect(dbh)) {
  522. release_table(table);
  523. release_database(dbh);
  524. return -1;
  525. }
  526. /* Create the first part of the query using the first parameter/value pairs we just extracted
  527. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  528. ESCAPE_STRING(buf, newval);
  529. ast_str_set(&sql, 0, "UPDATE %s SET `%s` = '%s'", tablename, newparam, ast_str_buffer(buf));
  530. /* If the column length isn't long enough, give a chance to lengthen it. */
  531. if (strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0) {
  532. internal_require(database, tablename, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL);
  533. }
  534. while ((newparam = va_arg(ap, const char *))) {
  535. newval = va_arg(ap, const char *);
  536. /* If the column is not within the table, then skip it */
  537. if (!(column = find_column(table, newparam))) {
  538. ast_log(LOG_WARNING, "Attempted to update column '%s' in table '%s', but column does not exist!\n", newparam, tablename);
  539. continue;
  540. }
  541. ESCAPE_STRING(buf, newval);
  542. ast_str_append(&sql, 0, ", `%s` = '%s'", newparam, ast_str_buffer(buf));
  543. /* If the column length isn't long enough, give a chance to lengthen it. */
  544. if (strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0) {
  545. internal_require(database, tablename, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL);
  546. }
  547. }
  548. va_end(ap);
  549. ESCAPE_STRING(buf, lookup);
  550. ast_str_append(&sql, 0, " WHERE `%s` = '%s'", keyfield, ast_str_buffer(buf));
  551. ast_debug(1, "MySQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
  552. /* Execution. */
  553. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  554. ast_log(LOG_WARNING, "MySQL RealTime: Failed to update database: %s\n", mysql_error(&dbh->handle));
  555. release_table(table);
  556. release_database(dbh);
  557. return -1;
  558. }
  559. numrows = mysql_affected_rows(&dbh->handle);
  560. release_table(table);
  561. release_database(dbh);
  562. ast_debug(1, "MySQL RealTime: Updated %llu rows on table: %s\n", numrows, tablename);
  563. /* From http://dev.mysql.com/doc/mysql/en/mysql-affected-rows.html
  564. * An integer greater than zero indicates the number of rows affected
  565. * Zero indicates that no records were updated
  566. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  567. */
  568. return (int)numrows;
  569. }
  570. static int update2_mysql(const char *database, const char *tablename, va_list ap)
  571. {
  572. struct mysql_conn *dbh;
  573. my_ulonglong numrows;
  574. int first = 1;
  575. const char *newparam, *newval;
  576. struct ast_str *sql = ast_str_thread_get(&sql_buf, 100), *buf = ast_str_thread_get(&scratch_buf, 100);
  577. struct ast_str *where = ast_str_thread_get(&sql2_buf, 100);
  578. struct tables *table;
  579. struct columns *column = NULL;
  580. if (!tablename) {
  581. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  582. return -1;
  583. }
  584. if (!(dbh = find_database(database, 1))) {
  585. ast_log(LOG_ERROR, "Invalid database specified: %s\n", database);
  586. return -1;
  587. }
  588. if (!(table = find_table(database, tablename))) {
  589. ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
  590. release_database(dbh);
  591. return -1;
  592. }
  593. if (!sql || !buf || !where) {
  594. release_database(dbh);
  595. release_table(table);
  596. return -1;
  597. }
  598. ast_str_set(&sql, 0, "UPDATE %s SET", tablename);
  599. ast_str_set(&where, 0, "WHERE");
  600. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  601. if (!mysql_reconnect(dbh)) {
  602. release_table(table);
  603. release_database(dbh);
  604. return -1;
  605. }
  606. while ((newparam = va_arg(ap, const char *))) {
  607. if (!(column = find_column(table, newparam))) {
  608. ast_log(LOG_ERROR, "Updating on column '%s', but that column does not exist within the table '%s'!\n", newparam, tablename);
  609. release_table(table);
  610. release_database(dbh);
  611. return -1;
  612. }
  613. if (!(newval = va_arg(ap, const char *))) {
  614. ast_log(LOG_ERROR, "Invalid arguments: no value specified for column '%s' on '%s@%s'\n", newparam, tablename, database);
  615. release_table(table);
  616. release_database(dbh);
  617. return -1;
  618. }
  619. ESCAPE_STRING(buf, newval);
  620. ast_str_append(&where, 0, "%s `%s` = '%s'", first ? "" : " AND", newparam, ast_str_buffer(buf));
  621. first = 0;
  622. /* If the column length isn't long enough, give a chance to lengthen it. */
  623. if (strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0) {
  624. internal_require(database, tablename, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL);
  625. }
  626. }
  627. first = 1;
  628. while ((newparam = va_arg(ap, const char *))) {
  629. if (!(newval = va_arg(ap, const char *))) {
  630. ast_log(LOG_ERROR, "Invalid arguments: no value specified for column '%s' on '%s@%s'\n", newparam, tablename, database);
  631. release_table(table);
  632. release_database(dbh);
  633. return -1;
  634. }
  635. /* If the column is not within the table, then skip it */
  636. if (!(column = find_column(table, newparam))) {
  637. ast_log(LOG_WARNING, "Attempted to update column '%s' in table '%s', but column does not exist!\n", newparam, tablename);
  638. continue;
  639. }
  640. ESCAPE_STRING(buf, newval);
  641. ast_str_append(&sql, 0, "%s `%s` = '%s'", first ? "" : ",", newparam, ast_str_buffer(buf));
  642. first = 0;
  643. /* If the column length isn't long enough, give a chance to lengthen it. */
  644. if (strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0) {
  645. internal_require(database, tablename, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL);
  646. }
  647. }
  648. va_end(ap);
  649. release_table(table);
  650. ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
  651. ast_debug(1, "MySQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
  652. /* Execution. */
  653. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  654. ast_log(LOG_WARNING, "MySQL RealTime: Failed to update database: %s\n", mysql_error(&dbh->handle));
  655. release_table(table);
  656. release_database(dbh);
  657. return -1;
  658. }
  659. numrows = mysql_affected_rows(&dbh->handle);
  660. release_database(dbh);
  661. ast_debug(1, "MySQL RealTime: Updated %llu rows on table: %s\n", numrows, tablename);
  662. /* From http://dev.mysql.com/doc/mysql/en/mysql-affected-rows.html
  663. * An integer greater than zero indicates the number of rows affected
  664. * Zero indicates that no records were updated
  665. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  666. */
  667. return (int)numrows;
  668. }
  669. static int store_mysql(const char *database, const char *table, va_list ap)
  670. {
  671. struct mysql_conn *dbh;
  672. my_ulonglong insertid;
  673. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  674. struct ast_str *sql2 = ast_str_thread_get(&sql2_buf, 16);
  675. struct ast_str *buf = ast_str_thread_get(&scratch_buf, 16);
  676. const char *newparam, *newval;
  677. if (!(dbh = find_database(database, 1))) {
  678. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: '%s' (check res_mysql.conf)\n", database);
  679. return -1;
  680. }
  681. if (!table) {
  682. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  683. release_database(dbh);
  684. return -1;
  685. }
  686. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  687. newparam = va_arg(ap, const char *);
  688. newval = va_arg(ap, const char *);
  689. if (!newparam || !newval) {
  690. ast_log(LOG_WARNING, "MySQL RealTime: Realtime storage requires at least 1 parameter and 1 value to search on.\n");
  691. release_database(dbh);
  692. return -1;
  693. }
  694. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  695. if (!mysql_reconnect(dbh)) {
  696. release_database(dbh);
  697. return -1;
  698. }
  699. /* Create the first part of the query using the first parameter/value pairs we just extracted
  700. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  701. ESCAPE_STRING(buf, newval);
  702. ast_str_set(&sql, 0, "INSERT INTO %s (`%s`", table, newparam);
  703. ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
  704. internal_require(database, table, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL);
  705. while ((newparam = va_arg(ap, const char *))) {
  706. if ((newval = va_arg(ap, const char *))) {
  707. ESCAPE_STRING(buf, newval);
  708. } else {
  709. ast_str_reset(buf);
  710. }
  711. if (internal_require(database, table, newparam, RQ_CHAR, ast_str_strlen(buf), SENTINEL) == 0) {
  712. ast_str_append(&sql, 0, ", `%s`", newparam);
  713. ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
  714. }
  715. }
  716. va_end(ap);
  717. ast_str_append(&sql, 0, "%s)", ast_str_buffer(sql2));
  718. ast_debug(1,"MySQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql));
  719. /* Execution. */
  720. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  721. ast_log(LOG_WARNING, "MySQL RealTime: Failed to insert into database: %s\n", mysql_error(&dbh->handle));
  722. release_database(dbh);
  723. return -1;
  724. }
  725. /*!\note The return value is non-portable and may change in future versions. */
  726. insertid = mysql_insert_id(&dbh->handle);
  727. release_database(dbh);
  728. ast_debug(1, "MySQL RealTime: row inserted on table: %s, id: %llu\n", table, insertid);
  729. /* From http://dev.mysql.com/doc/mysql/en/mysql-affected-rows.html
  730. * An integer greater than zero indicates the number of rows affected
  731. * Zero indicates that no records were updated
  732. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  733. */
  734. return (int)insertid;
  735. }
  736. static int destroy_mysql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
  737. {
  738. struct mysql_conn *dbh;
  739. my_ulonglong numrows;
  740. struct ast_str *sql = ast_str_thread_get(&sql_buf, 16);
  741. struct ast_str *buf = ast_str_thread_get(&scratch_buf, 16);
  742. const char *newparam, *newval;
  743. if (!(dbh = find_database(database, 1))) {
  744. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: '%s' (check res_mysql.conf)\n", database);
  745. return -1;
  746. }
  747. if (!table) {
  748. ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
  749. release_database(dbh);
  750. return -1;
  751. }
  752. /* Get the first parameter and first value in our list of passed paramater/value pairs */
  753. /* newparam = va_arg(ap, const char *);
  754. newval = va_arg(ap, const char *);*/
  755. if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup)) {
  756. ast_log(LOG_WARNING, "MySQL RealTime: Realtime destroying requires at least 1 parameter and 1 value to search on.\n");
  757. release_database(dbh);
  758. return -1;
  759. }
  760. /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
  761. if (!mysql_reconnect(dbh)) {
  762. release_database(dbh);
  763. return -1;
  764. }
  765. /* Create the first part of the query using the first parameter/value pairs we just extracted
  766. If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
  767. ESCAPE_STRING(buf, lookup);
  768. ast_str_set(&sql, 0, "DELETE FROM %s WHERE `%s` = '%s'", table, keyfield, ast_str_buffer(buf));
  769. while ((newparam = va_arg(ap, const char *))) {
  770. newval = va_arg(ap, const char *);
  771. ESCAPE_STRING(buf, newval);
  772. ast_str_append(&sql, 0, " AND `%s` = '%s'", newparam, ast_str_buffer(buf));
  773. }
  774. va_end(ap);
  775. ast_debug(1, "MySQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
  776. /* Execution. */
  777. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  778. ast_log(LOG_WARNING, "MySQL RealTime: Failed to delete from database: %s\n", mysql_error(&dbh->handle));
  779. release_database(dbh);
  780. return -1;
  781. }
  782. numrows = mysql_affected_rows(&dbh->handle);
  783. release_database(dbh);
  784. ast_debug(1, "MySQL RealTime: Deleted %llu rows on table: %s\n", numrows, table);
  785. /* From http://dev.mysql.com/doc/mysql/en/mysql-affected-rows.html
  786. * An integer greater than zero indicates the number of rows affected
  787. * Zero indicates that no records were updated
  788. * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
  789. */
  790. return (int)numrows;
  791. }
  792. static struct ast_config *config_mysql(const char *database, const char *table, const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *unused, const char *who_asked)
  793. {
  794. struct mysql_conn *dbh;
  795. MYSQL_RES *result;
  796. MYSQL_ROW row;
  797. my_ulonglong num_rows;
  798. struct ast_variable *new_v;
  799. struct ast_category *cur_cat = NULL;
  800. struct ast_str *sql = ast_str_thread_get(&sql_buf, 200);
  801. char last[80] = "";
  802. int last_cat_metric = 0;
  803. ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
  804. if (!file || !strcmp(file, RES_CONFIG_MYSQL_CONF)) {
  805. ast_log(LOG_WARNING, "MySQL RealTime: Cannot configure myself.\n");
  806. return NULL;
  807. }
  808. if (!(dbh = find_database(database, 0))) {
  809. ast_log(LOG_WARNING, "MySQL RealTime: Invalid database specified: '%s' (check res_mysql.conf)\n", database);
  810. return NULL;
  811. }
  812. ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s WHERE filename='%s' and commented=0 ORDER BY filename, cat_metric desc, var_metric asc, category, var_name, var_val, id", table, file);
  813. ast_debug(1, "MySQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
  814. /* We now have our complete statement; Lets connect to the server and execute it. */
  815. if (!mysql_reconnect(dbh)) {
  816. return NULL;
  817. }
  818. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  819. ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
  820. ast_debug(1, "MySQL RealTime: Query: %s\n", ast_str_buffer(sql));
  821. ast_debug(1, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&dbh->handle));
  822. release_database(dbh);
  823. return NULL;
  824. }
  825. if ((result = mysql_store_result(&dbh->handle))) {
  826. num_rows = mysql_num_rows(result);
  827. ast_debug(1, "MySQL RealTime: Found %llu rows.\n", num_rows);
  828. /* There might exist a better way to access the column names other than counting,
  829. * but I believe that would require another loop that we don't need. */
  830. while ((row = mysql_fetch_row(result))) {
  831. if (!strcmp(row[1], "#include")) {
  832. if (!ast_config_internal_load(row[2], cfg, config_flags, "", who_asked)) {
  833. mysql_free_result(result);
  834. release_database(dbh);
  835. return NULL;
  836. }
  837. continue;
  838. }
  839. if (strcmp(last, row[0]) || last_cat_metric != atoi(row[3])) {
  840. if (!(cur_cat = ast_category_new(row[0], "", -1))) {
  841. ast_log(LOG_WARNING, "Out of memory!\n");
  842. break;
  843. }
  844. strcpy(last, row[0]);
  845. last_cat_metric = atoi(row[3]);
  846. ast_category_append(cfg, cur_cat);
  847. }
  848. new_v = ast_variable_new(row[1], row[2], "");
  849. if (cur_cat)
  850. ast_variable_append(cur_cat, new_v);
  851. }
  852. } else {
  853. ast_log(LOG_WARNING, "MySQL RealTime: Could not find config '%s' in database.\n", file);
  854. }
  855. mysql_free_result(result);
  856. release_database(dbh);
  857. return cfg;
  858. }
  859. static int unload_mysql(const char *database, const char *tablename)
  860. {
  861. struct tables *cur;
  862. AST_LIST_LOCK(&mysql_tables);
  863. AST_LIST_TRAVERSE_SAFE_BEGIN(&mysql_tables, cur, list) {
  864. if (strcmp(cur->name, tablename) == 0) {
  865. AST_LIST_REMOVE_CURRENT(list);
  866. destroy_table(cur);
  867. break;
  868. }
  869. }
  870. AST_LIST_TRAVERSE_SAFE_END
  871. AST_LIST_UNLOCK(&mysql_tables);
  872. return cur ? 0 : -1;
  873. }
  874. static int modify_mysql(const char *database, const char *tablename, struct columns *column, require_type type, int len)
  875. {
  876. /*!\note Cannot use ANY of the same scratch space as is used in other functions, as this one is interspersed. */
  877. struct ast_str *sql = ast_str_thread_get(&modify_buf, 100), *escbuf = ast_str_thread_get(&modify2_buf, 100);
  878. struct ast_str *typestr = ast_str_thread_get(&modify3_buf, 30);
  879. int waschar = strncasecmp(column->type, "char", 4) == 0 ? 1 : 0;
  880. int wasvarchar = strncasecmp(column->type, "varchar", 7) == 0 ? 1 : 0;
  881. int res = 0;
  882. struct mysql_conn *dbh;
  883. if (!(dbh = find_database(database, 1))) {
  884. return -1;
  885. }
  886. do {
  887. if (type == RQ_CHAR || waschar || wasvarchar) {
  888. if (wasvarchar) {
  889. ast_str_set(&typestr, 0, "VARCHAR(%d)", len);
  890. } else {
  891. ast_str_set(&typestr, 0, "CHAR(%d)", len);
  892. }
  893. } else if (type == RQ_UINTEGER1) {
  894. ast_str_set(&typestr, 0, "tinyint(3) unsigned");
  895. } else if (type == RQ_INTEGER1) {
  896. ast_str_set(&typestr, 0, "tinyint(4)");
  897. } else if (type == RQ_UINTEGER2) {
  898. ast_str_set(&typestr, 0, "smallint(5) unsigned");
  899. } else if (type == RQ_INTEGER2) {
  900. ast_str_set(&typestr, 0, "smallint(6)");
  901. } else if (type == RQ_UINTEGER3) {
  902. ast_str_set(&typestr, 0, "mediumint(8) unsigned");
  903. } else if (type == RQ_INTEGER3) {
  904. ast_str_set(&typestr, 0, "mediumint(8)");
  905. } else if (type == RQ_UINTEGER4) {
  906. ast_str_set(&typestr, 0, "int(10) unsigned");
  907. } else if (type == RQ_INTEGER4) {
  908. ast_str_set(&typestr, 0, "int(11)");
  909. } else if (type == RQ_UINTEGER8) {
  910. ast_str_set(&typestr, 0, "bigint(19) unsigned");
  911. } else if (type == RQ_INTEGER8) {
  912. ast_str_set(&typestr, 0, "bigint(20)");
  913. } else if (type == RQ_DATETIME) {
  914. ast_str_set(&typestr, 0, "datetime");
  915. } else if (type == RQ_DATE) {
  916. ast_str_set(&typestr, 0, "date");
  917. } else if (type == RQ_FLOAT) {
  918. ast_str_set(&typestr, 0, "FLOAT(%d,2)", len);
  919. } else {
  920. ast_log(LOG_ERROR, "Unknown type (should NEVER happen)\n");
  921. res = -1;
  922. break;
  923. }
  924. ast_str_set(&sql, 0, "ALTER TABLE %s MODIFY `%s` %s", tablename, column->name, ast_str_buffer(typestr));
  925. if (!column->null) {
  926. ast_str_append(&sql, 0, " NOT NULL");
  927. }
  928. if (!ast_strlen_zero(column->dflt)) {
  929. ESCAPE_STRING(escbuf, column->dflt);
  930. ast_str_append(&sql, 0, " DEFAULT '%s'", ast_str_buffer(escbuf));
  931. }
  932. if (!mysql_reconnect(dbh)) {
  933. ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
  934. res = -1;
  935. break;
  936. }
  937. /* Execution. */
  938. if (mysql_real_query(&dbh->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  939. ast_log(LOG_WARNING, "MySQL RealTime: Failed to modify database: %s\n", mysql_error(&dbh->handle));
  940. ast_debug(1, "MySQL RealTime: Query: %s\n", ast_str_buffer(sql));
  941. res = -1;
  942. }
  943. } while (0);
  944. release_database(dbh);
  945. return res;
  946. }
  947. #define PICK_WHICH_ALTER_ACTION(stringtype) \
  948. if (table->database->requirements == RQ_WARN) { \
  949. ast_log(LOG_WARNING, "Realtime table %s@%s: column '%s' may not be large enough for " \
  950. "the required data length: %d (detected stringtype)\n", \
  951. tablename, database, column->name, size); \
  952. res = -1; \
  953. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) { \
  954. table_altered = 1; \
  955. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) { \
  956. table_altered = 1; \
  957. } else { \
  958. res = -1; \
  959. }
  960. static int require_mysql(const char *database, const char *tablename, va_list ap)
  961. {
  962. struct columns *column;
  963. struct tables *table = find_table(database, tablename);
  964. char *elm;
  965. int type, size, res = 0, table_altered = 0;
  966. if (!table) {
  967. ast_log(LOG_WARNING, "Table %s not found in database. This table should exist if you're using realtime.\n", tablename);
  968. return -1;
  969. }
  970. while ((elm = va_arg(ap, char *))) {
  971. type = va_arg(ap, require_type);
  972. size = va_arg(ap, int);
  973. AST_LIST_TRAVERSE(&table->columns, column, list) {
  974. if (strcmp(column->name, elm) == 0) {
  975. /* Char can hold anything, as long as it is large enough */
  976. if (strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0) {
  977. if ((size > column->len) && column->len != -1) {
  978. if (table->database->requirements == RQ_WARN) {
  979. ast_log(LOG_WARNING, "Realtime table %s@%s: Column '%s' should be at least %d long, but is only %d long.\n", database, tablename, column->name, size, column->len);
  980. res = -1;
  981. } else if (modify_mysql(database, tablename, column, type, size) == 0) {
  982. table_altered = 1;
  983. } else {
  984. res = -1;
  985. }
  986. }
  987. } else if (strcasestr(column->type, "unsigned")) {
  988. if (!ast_rq_is_int(type)) {
  989. if (table->database->requirements == RQ_WARN) {
  990. ast_log(LOG_WARNING, "Realtime table %s@%s: column '%s' cannot be type '%s' (need %s)\n",
  991. database, tablename, column->name, column->type,
  992. type == RQ_CHAR ? "char" : type == RQ_FLOAT ? "float" :
  993. type == RQ_DATETIME ? "datetime" : type == RQ_DATE ? "date" : "a rather stiff drink");
  994. res = -1;
  995. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  996. table_altered = 1;
  997. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  998. table_altered = 1;
  999. } else {
  1000. res = -1;
  1001. }
  1002. } else if (strncasecmp(column->type, "tinyint", 1) == 0) {
  1003. if (type != RQ_UINTEGER1) {
  1004. PICK_WHICH_ALTER_ACTION(unsigned tinyint)
  1005. }
  1006. } else if (strncasecmp(column->type, "smallint", 1) == 0) {
  1007. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 && type != RQ_UINTEGER2) {
  1008. PICK_WHICH_ALTER_ACTION(unsigned smallint)
  1009. }
  1010. } else if (strncasecmp(column->type, "mediumint", 1) == 0) {
  1011. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1012. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1013. type != RQ_UINTEGER3) {
  1014. PICK_WHICH_ALTER_ACTION(unsigned mediumint)
  1015. }
  1016. } else if (strncasecmp(column->type, "int", 1) == 0) {
  1017. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1018. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1019. type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
  1020. type != RQ_UINTEGER4) {
  1021. PICK_WHICH_ALTER_ACTION(unsigned int)
  1022. }
  1023. } else if (strncasecmp(column->type, "bigint", 1) == 0) {
  1024. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1025. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1026. type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
  1027. type != RQ_UINTEGER4 && type != RQ_INTEGER4 &&
  1028. type != RQ_UINTEGER8) {
  1029. PICK_WHICH_ALTER_ACTION(unsigned bigint)
  1030. }
  1031. }
  1032. } else if (strcasestr(column->type, "int")) {
  1033. if (!ast_rq_is_int(type)) {
  1034. if (table->database->requirements == RQ_WARN) {
  1035. ast_log(LOG_WARNING, "Realtime table %s@%s: column '%s' cannot be type '%s' (need %s)\n",
  1036. database, tablename, column->name, column->type,
  1037. type == RQ_CHAR ? "char" : type == RQ_FLOAT ? "float" :
  1038. type == RQ_DATETIME ? "datetime" : type == RQ_DATE ? "date" :
  1039. "to get a life, rather than writing silly error messages");
  1040. res = -1;
  1041. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  1042. table_altered = 1;
  1043. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  1044. table_altered = 1;
  1045. } else {
  1046. res = -1;
  1047. }
  1048. } else if (strncasecmp(column->type, "tinyint", 1) == 0) {
  1049. if (type != RQ_INTEGER1) {
  1050. PICK_WHICH_ALTER_ACTION(tinyint)
  1051. }
  1052. } else if (strncasecmp(column->type, "smallint", 1) == 0) {
  1053. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 && type != RQ_INTEGER2) {
  1054. PICK_WHICH_ALTER_ACTION(smallint)
  1055. }
  1056. } else if (strncasecmp(column->type, "mediumint", 1) == 0) {
  1057. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1058. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1059. type != RQ_INTEGER3) {
  1060. PICK_WHICH_ALTER_ACTION(mediumint)
  1061. }
  1062. } else if (strncasecmp(column->type, "int", 1) == 0) {
  1063. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1064. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1065. type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
  1066. type != RQ_INTEGER4) {
  1067. PICK_WHICH_ALTER_ACTION(int)
  1068. }
  1069. } else if (strncasecmp(column->type, "bigint", 1) == 0) {
  1070. if (type != RQ_UINTEGER1 && type != RQ_INTEGER1 &&
  1071. type != RQ_UINTEGER2 && type != RQ_INTEGER2 &&
  1072. type != RQ_UINTEGER3 && type != RQ_INTEGER3 &&
  1073. type != RQ_UINTEGER4 && type != RQ_INTEGER4 &&
  1074. type != RQ_INTEGER8) {
  1075. PICK_WHICH_ALTER_ACTION(bigint)
  1076. }
  1077. }
  1078. } else if (strncmp(column->type, "float", 5) == 0 && !ast_rq_is_int(type) && type != RQ_FLOAT) {
  1079. if (table->database->requirements == RQ_WARN) {
  1080. ast_log(LOG_WARNING, "Realtime table %s@%s: Column %s cannot be a %s\n", tablename, database, column->name, column->type);
  1081. res = -1;
  1082. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  1083. table_altered = 1;
  1084. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  1085. table_altered = 1;
  1086. } else {
  1087. res = -1;
  1088. }
  1089. } else if ((strncmp(column->type, "datetime", 8) == 0 || strncmp(column->type, "timestamp", 9) == 0) && type != RQ_DATETIME) {
  1090. if (table->database->requirements == RQ_WARN) {
  1091. ast_log(LOG_WARNING, "Realtime table %s@%s: Column %s cannot be a %s\n", tablename, database, column->name, column->type);
  1092. res = -1;
  1093. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  1094. table_altered = 1;
  1095. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  1096. table_altered = 1;
  1097. } else {
  1098. res = -1;
  1099. }
  1100. } else if ((strncmp(column->type, "date", 4) == 0) && type != RQ_DATE) {
  1101. if (table->database->requirements == RQ_WARN) {
  1102. ast_log(LOG_WARNING, "Realtime table %s@%s: Column %s cannot be a %s\n", tablename, database, column->name, column->type);
  1103. res = -1;
  1104. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  1105. table_altered = 1;
  1106. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  1107. table_altered = 1;
  1108. } else {
  1109. res = -1;
  1110. }
  1111. } else { /* Other, possibly unsupported types? */
  1112. if (table->database->requirements == RQ_WARN) {
  1113. ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
  1114. res = -1;
  1115. } else if (table->database->requirements == RQ_CREATECLOSE && modify_mysql(database, tablename, column, type, size) == 0) {
  1116. table_altered = 1;
  1117. } else if (table->database->requirements == RQ_CREATECHAR && modify_mysql(database, tablename, column, RQ_CHAR, size) == 0) {
  1118. table_altered = 1;
  1119. } else {
  1120. }
  1121. }
  1122. break;
  1123. }
  1124. }
  1125. if (!column) {
  1126. if (table->database->requirements == RQ_WARN) {
  1127. ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
  1128. } else {
  1129. struct ast_str *sql = ast_str_thread_get(&modify_buf, 100), *fieldtype = ast_str_thread_get(&modify3_buf, 16);
  1130. if (table->database->requirements == RQ_CREATECHAR || type == RQ_CHAR) {
  1131. ast_str_set(&fieldtype, 0, "CHAR(%d)", size);
  1132. } else if (type == RQ_UINTEGER1 || type == RQ_UINTEGER2 || type == RQ_UINTEGER3 || type == RQ_UINTEGER4 || type == RQ_UINTEGER8) {
  1133. if (type == RQ_UINTEGER1) {
  1134. ast_str_set(&fieldtype, 0, "TINYINT(3) UNSIGNED");
  1135. } else if (type == RQ_UINTEGER2) {
  1136. ast_str_set(&fieldtype, 0, "SMALLINT(5) UNSIGNED");
  1137. } else if (type == RQ_UINTEGER3) {
  1138. ast_str_set(&fieldtype, 0, "MEDIUMINT(8) UNSIGNED");
  1139. } else if (type == RQ_UINTEGER4) {
  1140. ast_str_set(&fieldtype, 0, "INT(10) UNSIGNED");
  1141. } else if (type == RQ_UINTEGER8) {
  1142. ast_str_set(&fieldtype, 0, "BIGINT(20) UNSIGNED");
  1143. } else {
  1144. ast_log(LOG_WARNING, "Somebody should check this code for a rather large bug... it's about to squash Tokyo.\n");
  1145. continue;
  1146. }
  1147. } else if (ast_rq_is_int(type)) {
  1148. if (type == RQ_INTEGER1) {
  1149. ast_str_set(&fieldtype, 0, "TINYINT(3)");
  1150. } else if (type == RQ_INTEGER2) {
  1151. ast_str_set(&fieldtype, 0, "SMALLINT(5)");
  1152. } else if (type == RQ_INTEGER3) {
  1153. ast_str_set(&fieldtype, 0, "MEDIUMINT(8)");
  1154. } else if (type == RQ_INTEGER4) {
  1155. ast_str_set(&fieldtype, 0, "INT(10)");
  1156. } else if (type == RQ_INTEGER8) {
  1157. ast_str_set(&fieldtype, 0, "BIGINT(20)");
  1158. } else {
  1159. ast_log(LOG_WARNING, "Somebody should check this code for a rather large bug... it's about to eat Cincinnati.\n");
  1160. continue;
  1161. }
  1162. } else if (type == RQ_FLOAT) {
  1163. ast_str_set(&fieldtype, 0, "FLOAT");
  1164. } else if (type == RQ_DATE) {
  1165. ast_str_set(&fieldtype, 0, "DATE");
  1166. } else if (type == RQ_DATETIME) {
  1167. ast_str_set(&fieldtype, 0, "DATETIME");
  1168. } else {
  1169. continue;
  1170. }
  1171. ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, ast_str_buffer(fieldtype));
  1172. ast_mutex_lock(&table->database->lock);
  1173. if (!mysql_reconnect(table->database)) {
  1174. ast_mutex_unlock(&table->database->lock);
  1175. ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
  1176. continue;
  1177. }
  1178. /* Execution. */
  1179. if (mysql_real_query(&table->database->handle, ast_str_buffer(sql), ast_str_strlen(sql))) {
  1180. ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
  1181. ast_debug(1, "MySQL RealTime: Query: %s\n", ast_str_buffer(sql));
  1182. ast_debug(1, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&table->database->handle));
  1183. } else {
  1184. table_altered = 1;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. release_table(table);
  1190. /* If we altered the table, we must refresh the cache */
  1191. if (table_altered) {
  1192. unload_mysql(database, tablename);
  1193. release_table(find_table(database, tablename));
  1194. }
  1195. return res;
  1196. }
  1197. static struct ast_config_engine mysql_engine = {
  1198. .name = "mysql",
  1199. .load_func = config_mysql,
  1200. .realtime_func = realtime_mysql,
  1201. .realtime_multi_func = realtime_multi_mysql,
  1202. .store_func = store_mysql,
  1203. .destroy_func = destroy_mysql,
  1204. .update_func = update_mysql,
  1205. .update2_func = update2_mysql,
  1206. .require_func = require_mysql,
  1207. .unload_func = unload_mysql,
  1208. };
  1209. static int load_module(void)
  1210. {
  1211. parse_config(0);
  1212. ast_config_engine_register(&mysql_engine);
  1213. if (option_verbose > 1)
  1214. ast_verbose(VERBOSE_PREFIX_2 "MySQL RealTime driver loaded.\n");
  1215. ast_cli_register_multiple(cli_realtime_mysql_status, sizeof(cli_realtime_mysql_status) / sizeof(struct ast_cli_entry));
  1216. return 0;
  1217. }
  1218. static int unload_module(void)
  1219. {
  1220. struct mysql_conn *cur;
  1221. struct tables *table;
  1222. ast_cli_unregister_multiple(cli_realtime_mysql_status, sizeof(cli_realtime_mysql_status) / sizeof(struct ast_cli_entry));
  1223. ast_config_engine_deregister(&mysql_engine);
  1224. if (option_verbose > 1)
  1225. ast_verbose(VERBOSE_PREFIX_2 "MySQL RealTime unloaded.\n");
  1226. ast_module_user_hangup_all();
  1227. usleep(1);
  1228. AST_RWLIST_WRLOCK(&databases);
  1229. while ((cur = AST_RWLIST_REMOVE_HEAD(&databases, list))) {
  1230. mysql_close(&cur->handle);
  1231. ast_mutex_destroy(&cur->lock);
  1232. ast_free(cur);
  1233. }
  1234. AST_RWLIST_UNLOCK(&databases);
  1235. /* Destroy cached table info */
  1236. AST_LIST_LOCK(&mysql_tables);
  1237. while ((table = AST_LIST_REMOVE_HEAD(&mysql_tables, list))) {
  1238. destroy_table(table);
  1239. }
  1240. AST_LIST_UNLOCK(&mysql_tables);
  1241. return 0;
  1242. }
  1243. static int reload(void)
  1244. {
  1245. parse_config(1);
  1246. if (option_verbose > 1) {
  1247. ast_verb(2, "MySQL RealTime reloaded.\n");
  1248. }
  1249. return 0;
  1250. }
  1251. static int parse_config(int reload)
  1252. {
  1253. struct ast_config *config = NULL;
  1254. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  1255. const char *catg;
  1256. struct mysql_conn *cur;
  1257. if ((config = ast_config_load(RES_CONFIG_MYSQL_CONF, config_flags)) == CONFIG_STATUS_FILEMISSING) {
  1258. /* Support old config file name */
  1259. config = ast_config_load(RES_CONFIG_MYSQL_CONF_OLD, config_flags);
  1260. }
  1261. if (config == CONFIG_STATUS_FILEMISSING) {
  1262. return 0;
  1263. } else if (config == CONFIG_STATUS_FILEUNCHANGED) {
  1264. return 0;
  1265. } else if (config == CONFIG_STATUS_FILEINVALID) {
  1266. ast_log(LOG_ERROR, "Not %sloading " RES_CONFIG_MYSQL_CONF "\n", reload ? "re" : "");
  1267. }
  1268. AST_RWLIST_WRLOCK(&databases);
  1269. for (catg = ast_category_browse(config, NULL); catg; catg = ast_category_browse(config, catg)) {
  1270. /* Does this category already exist? */
  1271. AST_RWLIST_TRAVERSE(&databases, cur, list) {
  1272. if (!strcmp(cur->unique_name, catg)) {
  1273. break;
  1274. }
  1275. }
  1276. if (!cur) {
  1277. if (!(cur = ast_calloc(1, sizeof(*cur) + strlen(catg) + 1))) {
  1278. ast_log(LOG_WARNING, "Could not allocate space for MySQL database '%s'\n", catg);
  1279. continue;
  1280. }
  1281. strcpy(cur->unique_name, catg); /* SAFE */
  1282. ast_mutex_init(&cur->lock);
  1283. AST_RWLIST_INSERT_TAIL(&databases, cur, list);
  1284. }
  1285. load_mysql_config(config, catg, cur);
  1286. }
  1287. AST_RWLIST_UNLOCK(&databases);
  1288. ast_config_destroy(config);
  1289. return 0;
  1290. }
  1291. static int load_mysql_config(struct ast_config *config, const char *category, struct mysql_conn *conn)
  1292. {
  1293. const char *s;
  1294. if (!(s = ast_variable_retrieve(config, category, "dbuser"))) {
  1295. ast_log(LOG_WARNING, "MySQL RealTime: No database user found, using 'asterisk' as default.\n");
  1296. s = "asterisk";
  1297. }
  1298. ast_copy_string(conn->user, s, sizeof(conn->user));
  1299. if (!(s = ast_variable_retrieve(config, category, "dbpass"))) {
  1300. ast_log(LOG_WARNING, "MySQL RealTime: No database password found, using 'asterisk' as default.\n");
  1301. s = "asterisk";
  1302. }
  1303. ast_copy_string(conn->pass, s, sizeof(conn->pass));
  1304. if (!(s = ast_variable_retrieve(config, category, "dbhost"))) {
  1305. ast_log(LOG_WARNING, "MySQL RealTime: No database host found, using localhost via socket.\n");
  1306. s = "";
  1307. }
  1308. ast_copy_string(conn->host, s, sizeof(conn->host));
  1309. if (!(s = ast_variable_retrieve(config, category, "dbname"))) {
  1310. ast_log(LOG_WARNING, "MySQL RealTime: No database name found, using 'asterisk' as default.\n");
  1311. s = "asterisk";
  1312. }
  1313. ast_copy_string(conn->name, s, sizeof(conn->name));
  1314. if (!(s = ast_variable_retrieve(config, category, "dbport"))) {
  1315. ast_log(LOG_WARNING, "MySQL RealTime: No database port found, using 3306 as default.\n");
  1316. conn->port = 3306;
  1317. } else
  1318. conn->port = atoi(s);
  1319. if (!(s = ast_variable_retrieve(config, category, "dbsock"))) {
  1320. if (ast_strlen_zero(conn->host)) {
  1321. char *paths[3] = { "/tmp/mysql.sock", "/var/lib/mysql/mysql.sock", "/var/run/mysqld/mysqld.sock" };
  1322. struct stat st;
  1323. int i;
  1324. for (i = 0; i < 3; i++) {
  1325. if (!stat(paths[i], &st)) {
  1326. ast_log(LOG_WARNING, "MySQL RealTime: No database socket found, using '%s' as default.\n", paths[i]);
  1327. ast_copy_string(conn->sock, paths[i], sizeof(conn->sock));
  1328. }
  1329. }
  1330. if (i == 3) {
  1331. ast_log(LOG_WARNING, "MySQL RealTime: No database socket found (and unable to detect a suitable path).\n");
  1332. return 0;
  1333. }
  1334. }
  1335. } else
  1336. ast_copy_string(conn->sock, s, sizeof(conn->sock));
  1337. if ((s = ast_variable_retrieve(config, category, "dbcharset"))) {
  1338. ast_copy_string(conn->charset, s, sizeof(conn->charset));
  1339. }
  1340. if (!(s = ast_variable_retrieve(config, category, "requirements"))) {
  1341. ast_log(LOG_WARNING, "MySQL realtime: no requirements setting found, using 'warn' as default.\n");
  1342. conn->requirements = RQ_WARN;
  1343. } else if (!strcasecmp(s, "createclose")) {
  1344. conn->requirements = RQ_CREATECLOSE;
  1345. } else if (!strcasecmp(s, "createchar")) {
  1346. conn->requirements = RQ_CREATECHAR;
  1347. } else if (!strcasecmp(s, "warn")) {
  1348. conn->requirements = RQ_WARN;
  1349. } else {
  1350. ast_log(LOG_WARNING, "MySQL realtime: unrecognized requirements setting '%s', using 'warn'\n", s);
  1351. conn->requirements = RQ_WARN;
  1352. }
  1353. if (!ast_strlen_zero(conn->host)) {
  1354. ast_debug(1, "MySQL RealTime host: %s\n", conn->host);
  1355. ast_debug(1, "MySQL RealTime port: %i\n", conn->port);
  1356. } else
  1357. ast_debug(1, "MySQL RealTime socket: %s\n", conn->sock);
  1358. ast_debug(1, "MySQL RealTime database name: %s\n", conn->name);
  1359. ast_debug(1, "MySQL RealTime user: %s\n", conn->user);
  1360. ast_debug(1, "MySQL RealTime password: %s\n", conn->pass);
  1361. if(conn->charset)
  1362. ast_debug(1, "MySQL RealTime charset: %s\n", conn->charset);
  1363. return 1;
  1364. }
  1365. static int mysql_reconnect(struct mysql_conn *conn)
  1366. {
  1367. #ifdef MYSQL_OPT_RECONNECT
  1368. my_bool trueval = 1;
  1369. #endif
  1370. /* mutex lock should have been locked before calling this function. */
  1371. reconnect_tryagain:
  1372. if ((!conn->connected) && (!ast_strlen_zero(conn->host) || conn->sock) && !ast_strlen_zero(conn->user) && !ast_strlen_zero(conn->name)) {
  1373. if (!mysql_init(&conn->handle)) {
  1374. ast_log(LOG_WARNING, "MySQL RealTime: Insufficient memory to allocate MySQL resource.\n");
  1375. conn->connected = 0;
  1376. return 0;
  1377. }
  1378. if(conn->charset && strlen(conn->charset) > 2){
  1379. char set_names[255];
  1380. char statement[512];
  1381. snprintf(set_names, sizeof(set_names), "SET NAMES %s", conn->charset);
  1382. mysql_real_escape_string(&conn->handle, statement, set_names, sizeof(set_names));
  1383. mysql_options(&conn->handle, MYSQL_INIT_COMMAND, set_names);
  1384. mysql_options(&conn->handle, MYSQL_SET_CHARSET_NAME, conn->charset);
  1385. }
  1386. if (mysql_real_connect(&conn->handle, conn->host, conn->user, conn->pass, conn->name, conn->port, conn->sock, 0)) {
  1387. #ifdef MYSQL_OPT_RECONNECT
  1388. /* The default is no longer to automatically reconnect on failure,
  1389. * (as of 5.0.3) so we have to set that option here. */
  1390. mysql_options(&conn->handle, MYSQL_OPT_RECONNECT, &trueval);
  1391. #endif
  1392. ast_debug(1, "MySQL RealTime: Successfully connected to database.\n");
  1393. conn->connected = 1;
  1394. conn->connect_time = time(NULL);
  1395. return 1;
  1396. } else {
  1397. ast_log(LOG_ERROR, "MySQL RealTime: Failed to connect database server %s on %s (err %d). Check debug for more info.\n", conn->name, !ast_strlen_zero(conn->host) ? conn->host : conn->sock, mysql_errno(&conn->handle));
  1398. ast_debug(1, "MySQL RealTime: Cannot Connect (%d): %s\n", mysql_errno(&conn->handle), mysql_error(&conn->handle));
  1399. conn->connected = 0;
  1400. conn->connect_time = 0;
  1401. return 0;
  1402. }
  1403. } else {
  1404. /* MySQL likes to return an error, even if it reconnects successfully.
  1405. * So the postman pings twice. */
  1406. if (mysql_ping(&conn->handle) != 0 && (usleep(1) + 2 > 0) && mysql_ping(&conn->handle) != 0) {
  1407. conn->connected = 0;
  1408. conn->connect_time = 0;
  1409. ast_log(LOG_ERROR, "MySQL RealTime: Ping failed (%d). Trying an explicit reconnect.\n", mysql_errno(&conn->handle));
  1410. ast_debug(1, "MySQL RealTime: Server Error (%d): %s\n", mysql_errno(&conn->handle), mysql_error(&conn->handle));
  1411. goto reconnect_tryagain;
  1412. }
  1413. if (!conn->connected) {
  1414. conn->connected = 1;
  1415. conn->connect_time = time(NULL);
  1416. }
  1417. if (mysql_select_db(&conn->handle, conn->name) != 0) {
  1418. ast_log(LOG_WARNING, "MySQL RealTime: Unable to select database: %s. Still Connected (%u) - %s.\n", conn->name, mysql_errno(&conn->handle), mysql_error(&conn->handle));
  1419. return 0;
  1420. }
  1421. ast_debug(1, "MySQL RealTime: Connection okay.\n");
  1422. return 1;
  1423. }
  1424. }
  1425. static char *handle_cli_realtime_mysql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1426. {
  1427. struct tables *cur;
  1428. int l, which;
  1429. char *ret = NULL;
  1430. switch (cmd) {
  1431. case CLI_INIT:
  1432. e->command = "realtime mysql cache";
  1433. e->usage =
  1434. "Usage: realtime mysql cache [<database> <table>]\n"
  1435. " Shows table cache for the MySQL RealTime driver\n";
  1436. return NULL;
  1437. case CLI_GENERATE:
  1438. if (a->argc < 4 || a->argc > 5) {
  1439. return NULL;
  1440. }
  1441. l = strlen(a->word);
  1442. which = 0;
  1443. if (a->argc == 5) {
  1444. AST_LIST_LOCK(&mysql_tables);
  1445. AST_LIST_TRAVERSE(&mysql_tables, cur, list) {
  1446. if (!strcasecmp(a->argv[3], cur->database->unique_name) && !strncasecmp(a->word, cur->name, l) && ++which > a->n) {
  1447. ret = ast_strdup(cur->name);
  1448. break;
  1449. }
  1450. }
  1451. AST_LIST_UNLOCK(&mysql_tables);
  1452. } else {
  1453. struct mysql_conn *cur;
  1454. AST_RWLIST_RDLOCK(&databases);
  1455. AST_RWLIST_TRAVERSE(&databases, cur, list) {
  1456. if (!strncasecmp(a->word, cur->unique_name, l) && ++which > a->n) {
  1457. ret = ast_strdup(cur->unique_name);
  1458. break;
  1459. }
  1460. }
  1461. AST_RWLIST_UNLOCK(&databases);
  1462. }
  1463. return ret;
  1464. }
  1465. if (a->argc == 3) {
  1466. /* List of tables */
  1467. AST_LIST_LOCK(&mysql_tables);
  1468. AST_LIST_TRAVERSE(&mysql_tables, cur, list) {
  1469. ast_cli(a->fd, "%20.20s %s\n", cur->database->unique_name, cur->name);
  1470. }
  1471. AST_LIST_UNLOCK(&mysql_tables);
  1472. } else if (a->argc == 4) {
  1473. int found = 0;
  1474. /* List of tables */
  1475. AST_LIST_LOCK(&mysql_tables);
  1476. AST_LIST_TRAVERSE(&mysql_tables, cur, list) {
  1477. if (!strcasecmp(cur->database->unique_name, a->argv[3])) {
  1478. ast_cli(a->fd, "%s\n", cur->name);
  1479. found = 1;
  1480. }
  1481. }
  1482. AST_LIST_UNLOCK(&mysql_tables);
  1483. if (!found) {
  1484. ast_cli(a->fd, "No tables cached within %s database\n", a->argv[3]);
  1485. }
  1486. } else if (a->argc == 5) {
  1487. /* List of columns */
  1488. if ((cur = find_table(a->argv[3], a->argv[4]))) {
  1489. struct columns *col;
  1490. ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[3]);
  1491. ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s\n", "Name", "Type", "Len");
  1492. AST_LIST_TRAVERSE(&cur->columns, col, list) {
  1493. ast_cli(a->fd, "%-20.20s %-20.20s %3d\n", col->name, col->type, col->len);
  1494. }
  1495. release_table(cur);
  1496. } else {
  1497. ast_cli(a->fd, "No such table '%s'\n", a->argv[3]);
  1498. }
  1499. }
  1500. return CLI_SUCCESS;
  1501. }
  1502. static char *handle_cli_realtime_mysql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1503. {
  1504. char status[256], status2[100] = "", type[20];
  1505. char *ret = NULL;
  1506. int ctime = 0, found = 0;
  1507. struct mysql_conn *cur;
  1508. int l = 0, which = 0;
  1509. switch (cmd) {
  1510. case CLI_INIT:
  1511. e->command = "realtime mysql status";
  1512. e->usage =
  1513. "Usage: realtime mysql status [<database>]\n"
  1514. " Shows connection information for the MySQL RealTime driver\n";
  1515. return NULL;
  1516. case CLI_GENERATE:
  1517. if (a->argc == 4) {
  1518. AST_RWLIST_RDLOCK(&databases);
  1519. AST_RWLIST_TRAVERSE(&databases, cur, list) {
  1520. if (!strncasecmp(a->word, cur->unique_name, l) && ++which > a->n) {
  1521. ret = ast_strdup(cur->unique_name);
  1522. break;
  1523. }
  1524. }
  1525. AST_RWLIST_UNLOCK(&databases);
  1526. }
  1527. return ret;
  1528. }
  1529. if (a->argc != 3)
  1530. return CLI_SHOWUSAGE;
  1531. AST_RWLIST_RDLOCK(&databases);
  1532. AST_RWLIST_TRAVERSE(&databases, cur, list) {
  1533. if (a->argc == 3 || (a->argc == 4 && !strcasecmp(a->argv[3], cur->unique_name))) {
  1534. found = 1;
  1535. if (mysql_reconnect(cur)) {
  1536. snprintf(type, sizeof(type), "connected to");
  1537. ctime = time(NULL) - cur->connect_time;
  1538. } else {
  1539. snprintf(type, sizeof(type), "configured for");
  1540. ctime = -1;
  1541. }
  1542. if (!ast_strlen_zero(cur->host)) {
  1543. snprintf(status, sizeof(status), "%s %s %s@%s, port %d", cur->unique_name, type, cur->name, cur->host, cur->port);
  1544. } else {
  1545. snprintf(status, sizeof(status), "%s %s %s on socket file %s", cur->unique_name, type, cur->name, cur->sock);
  1546. }
  1547. if (!ast_strlen_zero(cur->user)) {
  1548. snprintf(status2, sizeof(status2), " with username %s", cur->user);
  1549. } else {
  1550. status2[0] = '\0';
  1551. }
  1552. if (ctime > 31536000) {
  1553. ast_cli(a->fd, "%s%s for %.1f years.\n", status, status2, (double)ctime / 31536000.0);
  1554. } else if (ctime > 86400 * 30) {
  1555. ast_cli(a->fd, "%s%s for %d days.\n", status, status2, ctime / 86400);
  1556. } else if (ctime > 86400) {
  1557. ast_cli(a->fd, "%s%s for %d days, %d hours.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600);
  1558. } else if (ctime > 3600) {
  1559. ast_cli(a->fd, "%s%s for %d hours, %d minutes.\n", status, status2, ctime / 3600, (ctime % 3600) / 60);
  1560. } else if (ctime > 60) {
  1561. ast_cli(a->fd, "%s%s for %d minutes.\n", status, status2, ctime / 60);
  1562. } else if (ctime > -1) {
  1563. ast_cli(a->fd, "%s%s for %d seconds.\n", status, status2, ctime);
  1564. } else {
  1565. ast_cli(a->fd, "%s%s.\n", status, status2);
  1566. }
  1567. }
  1568. }
  1569. AST_RWLIST_UNLOCK(&databases);
  1570. if (!found) {
  1571. ast_cli(a->fd, "No connections configured.\n");
  1572. }
  1573. return CLI_SUCCESS;
  1574. }
  1575. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "MySQL RealTime Configuration Driver",
  1576. .load = load_module,
  1577. .unload = unload_module,
  1578. .reload = reload,
  1579. .load_pri = AST_MODPRI_REALTIME_DRIVER,
  1580. );