res_config_mysql.c 60 KB

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