res_config_mysql.c 52 KB

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