res_config_mysql.c 59 KB

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