git migration: Refactor the ASTERISK_FILE_VERSION macro
[asterisk/asterisk.git] / addons / cdr_mysql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * James Sharp <jsharp@psychoses.org>
5  *
6  * Modified August 2003
7  * Tilghman Lesher <asterisk__cdr__cdr_mysql__200308@the-tilghman.com>
8  *
9  * Modified August 6, 2005
10  * Joseph Benden <joe@thrallingpenguin.com>
11  * Added mysql connection timeout parameter
12  * Added an automatic reconnect as to not lose a cdr record
13  * Cleaned up the original code to match the coding guidelines
14  *
15  * Modified Juli 2006
16  * Martin Portmann <map@infinitum.ch>
17  * Added mysql ssl support
18  *
19  * See http://www.asterisk.org for more information about
20  * the Asterisk project. Please do not directly contact
21  * any of the maintainers of this project for assistance;
22  * the project provides a web site, mailing lists and IRC
23  * channels for your use.
24  *
25  * This program is free software, distributed under the terms of
26  * the GNU General Public License Version 2. See the LICENSE file
27  * at the top of the source tree.
28  */
29
30 /*!
31  * \file
32  * \brief MySQL CDR backend
33  * \ingroup cdr_drivers
34  */
35
36 /*** MODULEINFO
37         <depend>mysqlclient</depend>
38         <defaultenabled>no</defaultenabled>
39         <support_level>deprecated</support_level>
40         <replacement>cdr_adaptive_odbc</replacement>
41  ***/
42
43 #include "asterisk.h"
44
45 ASTERISK_REGISTER_FILE()
46
47 #include <mysql/mysql.h>
48 #include <mysql/errmsg.h>
49
50 #include "asterisk/config.h"
51 #include "asterisk/options.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/cdr.h"
54 #include "asterisk/module.h"
55 #include "asterisk/logger.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/strings.h"
58 #include "asterisk/linkedlists.h"
59 #include "asterisk/threadstorage.h"
60
61 #define DATE_FORMAT "%Y-%m-%d %T"
62
63 AST_THREADSTORAGE(sql1_buf);
64 AST_THREADSTORAGE(sql2_buf);
65 AST_THREADSTORAGE(escape_buf);
66
67 static const char desc[] = "MySQL CDR Backend";
68 static const char name[] = "mysql";
69 static const char config[] = "cdr_mysql.conf";
70
71 static struct ast_str *hostname = NULL, *dbname = NULL, *dbuser = NULL, *password = NULL, *dbsock = NULL, *dbtable = NULL, *dbcharset = NULL, *cdrzone = NULL;
72
73 static struct ast_str *ssl_ca = NULL, *ssl_cert = NULL, *ssl_key = NULL;
74
75 static int dbport = 0;
76 static int connected = 0;
77 static time_t connect_time = 0;
78 static int records = 0;
79 static int totalrecords = 0;
80 static int timeout = 0;
81 static int calldate_compat = 0;
82
83 AST_MUTEX_DEFINE_STATIC(mysql_lock);
84
85 struct unload_string {
86         AST_LIST_ENTRY(unload_string) entry;
87         struct ast_str *str;
88 };
89
90 static AST_LIST_HEAD_STATIC(unload_strings, unload_string);
91
92 struct column {
93         char *name;
94         char *cdrname;
95         char *staticvalue;
96         char *type;
97         AST_LIST_ENTRY(column) list;
98 };
99
100 /* Protected with mysql_lock */
101 static AST_RWLIST_HEAD_STATIC(columns, column);
102
103 static MYSQL mysql = { { NULL }, };
104
105 static char *handle_cli_cdr_mysql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
106 {
107         switch (cmd) {
108         case CLI_INIT:
109                 e->command = "cdr mysql status";
110                 e->usage =
111                         "Usage: cdr mysql status\n"
112                         "       Shows current connection status for cdr_mysql\n";
113                 return NULL;
114         case CLI_GENERATE:
115                 return NULL;
116         }
117
118         if (a->argc != 3)
119                 return CLI_SHOWUSAGE;
120
121         if (connected) {
122                 char status[256], status2[100] = "";
123                 int ctime = time(NULL) - connect_time;
124                 if (dbport)
125                         snprintf(status, 255, "Connected to %s@%s, port %d", ast_str_buffer(dbname), ast_str_buffer(hostname), dbport);
126                 else if (dbsock)
127                         snprintf(status, 255, "Connected to %s on socket file %s", ast_str_buffer(dbname), S_OR(ast_str_buffer(dbsock), "default"));
128                 else
129                         snprintf(status, 255, "Connected to %s@%s", ast_str_buffer(dbname), ast_str_buffer(hostname));
130
131                 if (!ast_strlen_zero(ast_str_buffer(dbuser)))
132                         snprintf(status2, 99, " with username %s", ast_str_buffer(dbuser));
133                 if (ast_str_strlen(dbtable))
134                         snprintf(status2, 99, " using table %s", ast_str_buffer(dbtable));
135                 if (ctime > 31536000) {
136                         ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 31536000, (ctime % 31536000) / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
137                 } else if (ctime > 86400) {
138                         ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
139                 } else if (ctime > 3600) {
140                         ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 3600, (ctime % 3600) / 60, ctime % 60);
141                 } else if (ctime > 60) {
142                         ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60, ctime % 60);
143                 } else {
144                         ast_cli(a->fd, "%s%s for %d seconds.\n", status, status2, ctime);
145                 }
146                 if (records == totalrecords)
147                         ast_cli(a->fd, "  Wrote %d records since last restart.\n", totalrecords);
148                 else
149                         ast_cli(a->fd, "  Wrote %d records since last restart and %d records since last reconnect.\n", totalrecords, records);
150         } else {
151                 ast_cli(a->fd, "Not currently connected to a MySQL server.\n");
152         }
153
154         return CLI_SUCCESS;
155 }
156
157 static struct ast_cli_entry cdr_mysql_status_cli[] = {
158         AST_CLI_DEFINE(handle_cli_cdr_mysql_status, "Show connection status of cdr_mysql"),
159 };
160
161 static int mysql_log(struct ast_cdr *cdr)
162 {
163         struct ast_str *sql1 = ast_str_thread_get(&sql1_buf, 1024), *sql2 = ast_str_thread_get(&sql2_buf, 1024);
164         int retries = 5;
165 #if MYSQL_VERSION_ID >= 50013
166         my_bool my_bool_true = 1;
167 #endif
168
169         if (!sql1 || !sql2) {
170                 ast_log(LOG_ERROR, "Memory error\n");
171                 return -1;
172         }
173
174         ast_mutex_lock(&mysql_lock);
175
176 db_reconnect:
177         if ((!connected) && (hostname || dbsock) && dbuser && password && dbname && dbtable ) {
178                 /* Attempt to connect */
179                 mysql_init(&mysql);
180                 /* Add option to quickly timeout the connection */
181                 if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
182                         ast_log(LOG_ERROR, "mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
183                 }
184 #if MYSQL_VERSION_ID >= 50013
185                 /* Add option for automatic reconnection */
186                 if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
187                         ast_log(LOG_ERROR, "mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
188                 }
189 #endif
190                 if (ssl_ca || ssl_cert || ssl_key) {
191                         mysql_ssl_set(&mysql, ssl_key ? ast_str_buffer(ssl_key) : NULL, ssl_cert ? ast_str_buffer(ssl_cert) : NULL, ssl_ca ? ast_str_buffer(ssl_ca) : NULL, NULL, NULL);
192                 }
193                 if (mysql_real_connect(&mysql, ast_str_buffer(hostname), ast_str_buffer(dbuser), ast_str_buffer(password), ast_str_buffer(dbname), dbport, dbsock && ast_str_strlen(dbsock) ? ast_str_buffer(dbsock) : NULL, ssl_ca ? CLIENT_SSL : 0)) {
194                         connected = 1;
195                         connect_time = time(NULL);
196                         records = 0;
197                         if (dbcharset) {
198                                 ast_str_set(&sql1, 0, "SET NAMES '%s'", ast_str_buffer(dbcharset));
199                                 mysql_real_query(&mysql, ast_str_buffer(sql1), ast_str_strlen(sql1));
200                                 ast_debug(1, "SQL command as follows: %s\n", ast_str_buffer(sql1));
201                         }
202                 } else {
203                         ast_log(LOG_ERROR, "Cannot connect to database server %s: (%d) %s\n", ast_str_buffer(hostname), mysql_errno(&mysql), mysql_error(&mysql));
204                         connected = 0;
205                 }
206         } else {
207                 /* Long connection - ping the server */
208                 int error;
209                 if ((error = mysql_ping(&mysql))) {
210                         connected = 0;
211                         records = 0;
212                         switch (mysql_errno(&mysql)) {
213                                 case CR_SERVER_GONE_ERROR:
214                                 case CR_SERVER_LOST:
215                                         ast_log(LOG_ERROR, "Server has gone away. Attempting to reconnect.\n");
216                                         break;
217                                 default:
218                                         ast_log(LOG_ERROR, "Unknown connection error: (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
219                         }
220                         retries--;
221                         if (retries) {
222                                 goto db_reconnect;
223                         } else {
224                                 ast_log(LOG_ERROR, "Retried to connect five times, giving up.\n");
225                         }
226                 }
227         }
228
229         if (connected) {
230                 int column_count = 0;
231                 char *cdrname;
232                 char workspace[2048], *value = NULL;
233                 struct column *entry;
234                 struct ast_str *escape = ast_str_thread_get(&escape_buf, 16);
235
236                 ast_str_set(&sql1, 0, "INSERT INTO %s (", AS_OR(dbtable, "cdr"));
237                 ast_str_set(&sql2, 0, ") VALUES (");
238
239                 AST_RWLIST_RDLOCK(&columns);
240                 AST_RWLIST_TRAVERSE(&columns, entry, list) {
241                         if (!strcmp(entry->name, "calldate")) {
242                                 /*!\note
243                                  * For some dumb reason, "calldate" used to be formulated using
244                                  * the datetime the record was posted, rather than the start
245                                  * time of the call.  If someone really wants the old compatible
246                                  * behavior, it's provided here.
247                                  */
248                                 if (calldate_compat) {
249                                         struct timeval tv = ast_tvnow();
250                                         struct ast_tm tm;
251                                         char timestr[128];
252                                         ast_localtime(&tv, &tm, ast_str_strlen(cdrzone) ? ast_str_buffer(cdrzone) : NULL);
253                                         ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
254                                         value = ast_strdupa(timestr);
255                                         cdrname = "calldate";
256                                 } else {
257                                         cdrname = "start";
258                                 }
259                         } else {
260                                 cdrname = entry->cdrname;
261                         }
262
263                         /* Construct SQL */
264
265                         /* Need the type and value to determine if we want the raw value or not */
266                         if (entry->staticvalue) {
267                                 value = ast_strdupa(entry->staticvalue);
268                         } else if ((!strcmp(cdrname, "start") ||
269                                  !strcmp(cdrname, "answer") ||
270                                  !strcmp(cdrname, "end") ||
271                                  !strcmp(cdrname, "disposition") ||
272                                  !strcmp(cdrname, "amaflags")) &&
273                                 (strstr(entry->type, "int") ||
274                                  strstr(entry->type, "dec") ||
275                                  strstr(entry->type, "float") ||
276                                  strstr(entry->type, "double") ||
277                                  strstr(entry->type, "real") ||
278                                  strstr(entry->type, "numeric") ||
279                                  strstr(entry->type, "fixed"))) {
280                                 ast_cdr_format_var(cdr, cdrname, &value, workspace, sizeof(workspace), 1);
281                         } else if (!strcmp(cdrname, "calldate")) {
282                                 /* Skip calldate - the value has already been dup'd */
283                         } else {
284                                 ast_cdr_format_var(cdr, cdrname, &value, workspace, sizeof(workspace), 0);
285                         }
286
287                         if (value) {
288                                 size_t valsz;
289
290                                 if (column_count++) {
291                                         ast_str_append(&sql1, 0, ",");
292                                         ast_str_append(&sql2, 0, ",");
293                                 }
294
295                                 if (!strcasecmp(cdrname, "billsec") &&
296                                         (strstr(entry->type, "float") ||
297                                         strstr(entry->type, "double") ||
298                                         strstr(entry->type, "decimal") ||
299                                         strstr(entry->type, "numeric") ||
300                                         strstr(entry->type, "real"))) {
301
302                                         if (!ast_tvzero(cdr->answer)) {
303                                                 snprintf(workspace, sizeof(workspace), "%lf",
304                                                         (double) (ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0));
305                                         } else {
306                                                 ast_copy_string(workspace, "0", sizeof(workspace));
307                                         }
308
309                                         if (!ast_strlen_zero(workspace)) {
310                                                 value = workspace;
311                                         }
312                                 }
313
314                                 if (!strcasecmp(cdrname, "duration") &&
315                                         (strstr(entry->type, "float") ||
316                                         strstr(entry->type, "double") ||
317                                         strstr(entry->type, "decimal") ||
318                                         strstr(entry->type, "numeric") ||
319                                         strstr(entry->type, "real"))) {
320
321                                         snprintf(workspace, sizeof(workspace), "%lf",
322                                                 (double) (ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0));
323
324                                         if (!ast_strlen_zero(workspace)) {
325                                                 value = workspace;
326                                         }
327                                 }
328
329                                 ast_str_make_space(&escape, (valsz = strlen(value)) * 2 + 1);
330                                 mysql_real_escape_string(&mysql, ast_str_buffer(escape), value, valsz);
331
332                                 ast_str_append(&sql1, 0, "`%s`", entry->name);
333                                 ast_str_append(&sql2, 0, "'%s'", ast_str_buffer(escape));
334                         }
335                 }
336                 AST_RWLIST_UNLOCK(&columns);
337
338                 ast_debug(1, "Inserting a CDR record.\n");
339                 ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
340
341                 ast_debug(1, "SQL command as follows: %s\n", ast_str_buffer(sql1));
342
343                 if (mysql_real_query(&mysql, ast_str_buffer(sql1), ast_str_strlen(sql1))) {
344                         ast_log(LOG_ERROR, "Failed to insert into database: (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
345                         mysql_close(&mysql);
346                         connected = 0;
347                 } else {
348                         records++;
349                         totalrecords++;
350                 }
351         }
352         ast_mutex_unlock(&mysql_lock);
353         return 0;
354 }
355
356 static int my_unload_module(int reload)
357
358         struct unload_string *us;
359         struct column *entry;
360
361         ast_cli_unregister_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
362
363         if (connected) {
364                 mysql_close(&mysql);
365                 connected = 0;
366                 records = 0;
367         }
368
369         AST_LIST_LOCK(&unload_strings);
370         while ((us = AST_LIST_REMOVE_HEAD(&unload_strings, entry))) {
371                 ast_free(us->str);
372                 ast_free(us);
373         }
374         AST_LIST_UNLOCK(&unload_strings);
375
376         if (!reload) {
377                 AST_RWLIST_WRLOCK(&columns);
378         }
379         while ((entry = AST_RWLIST_REMOVE_HEAD(&columns, list))) {
380                 ast_free(entry);
381         }
382         if (!reload) {
383                 AST_RWLIST_UNLOCK(&columns);
384         }
385
386         dbport = 0;
387         if (reload) {
388                 return ast_cdr_backend_suspend(name);
389         } else {
390                 return ast_cdr_unregister(name);
391         }
392 }
393
394 static int my_load_config_string(struct ast_config *cfg, const char *category, const char *variable, struct ast_str **field, const char *def)
395 {
396         struct unload_string *us;
397         const char *tmp;
398
399         if (!(us = ast_calloc(1, sizeof(*us))))
400                 return -1;
401
402         if (!(*field = ast_str_create(16))) {
403                 ast_free(us);
404                 return -1;
405         }
406
407         tmp = ast_variable_retrieve(cfg, category, variable);
408
409         ast_str_set(field, 0, "%s", tmp ? tmp : def);
410
411         us->str = *field;
412
413         AST_LIST_LOCK(&unload_strings);
414         AST_LIST_INSERT_HEAD(&unload_strings, us, entry);
415         AST_LIST_UNLOCK(&unload_strings);
416
417         return 0;
418 }
419
420 static int my_load_config_number(struct ast_config *cfg, const char *category, const char *variable, int *field, int def)
421 {
422         const char *tmp;
423
424         tmp = ast_variable_retrieve(cfg, category, variable);
425
426         if (!tmp || sscanf(tmp, "%30d", field) < 1)
427                 *field = def;
428
429         return 0;
430 }
431
432 static int my_load_module(int reload)
433 {
434         int res;
435         struct ast_config *cfg;
436         struct ast_variable *var;
437         /* CONFIG_STATUS_FILEUNCHANGED is impossible when config_flags is always 0,
438          * and it has to be zero, so a reload can be sent to tell the driver to
439          * rescan the table layout. */
440         struct ast_flags config_flags = { 0 };
441         struct column *entry;
442         char *temp;
443         struct ast_str *compat;
444         MYSQL_ROW row;
445         MYSQL_RES *result;
446         char sqldesc[128];
447 #if MYSQL_VERSION_ID >= 50013
448         my_bool my_bool_true = 1;
449 #endif
450
451         /* Cannot use a conditionally different flag, because the table layout may
452          * have changed, which is not detectable by config file change detection,
453          * but should still cause the configuration to be re-parsed. */
454         cfg = ast_config_load(config, config_flags);
455         if (cfg == CONFIG_STATUS_FILEMISSING) {
456                 ast_log(LOG_WARNING, "Unable to load config for mysql CDR's: %s\n", config);
457                 return AST_MODULE_LOAD_SUCCESS;
458         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
459                 ast_log(LOG_ERROR, "Unable to load configuration file '%s'\n", config);
460                 return AST_MODULE_LOAD_DECLINE;
461         }
462
463         if (reload) {
464                 AST_RWLIST_WRLOCK(&columns);
465                 my_unload_module(1);
466         }
467
468         var = ast_variable_browse(cfg, "global");
469         if (!var) {
470                 /* nothing configured */
471                 if (reload) {
472                         AST_RWLIST_UNLOCK(&columns);
473                 }
474                 ast_config_destroy(cfg);
475                 return AST_MODULE_LOAD_SUCCESS;
476         }
477
478         res = 0;
479
480         res |= my_load_config_string(cfg, "global", "hostname", &hostname, "localhost");
481         res |= my_load_config_string(cfg, "global", "dbname", &dbname, "astriskcdrdb");
482         res |= my_load_config_string(cfg, "global", "user", &dbuser, "root");
483         res |= my_load_config_string(cfg, "global", "sock", &dbsock, "");
484         res |= my_load_config_string(cfg, "global", "table", &dbtable, "cdr");
485         res |= my_load_config_string(cfg, "global", "password", &password, "");
486
487         res |= my_load_config_string(cfg, "global", "charset", &dbcharset, "");
488
489         res |= my_load_config_string(cfg, "global", "ssl_ca", &ssl_ca, "");
490         res |= my_load_config_string(cfg, "global", "ssl_cert", &ssl_cert, "");
491         res |= my_load_config_string(cfg, "global", "ssl_key", &ssl_key, "");
492
493         res |= my_load_config_number(cfg, "global", "port", &dbport, 0);
494         res |= my_load_config_number(cfg, "global", "timeout", &timeout, 0);
495         res |= my_load_config_string(cfg, "global", "compat", &compat, "no");
496         res |= my_load_config_string(cfg, "global", "cdrzone", &cdrzone, "");
497         if (ast_str_strlen(cdrzone) == 0) {
498                 for (; var; var = var->next) {
499                         if (!strcasecmp(var->name, "usegmtime") && ast_true(var->value)) {
500                                 ast_str_set(&cdrzone, 0, "UTC");
501                         }
502                 }
503         }
504
505         if (ast_true(ast_str_buffer(compat))) {
506                 calldate_compat = 1;
507         } else {
508                 calldate_compat = 0;
509         }
510
511         if (res < 0) {
512                 if (reload) {
513                         AST_RWLIST_UNLOCK(&columns);
514                 }
515                 ast_config_destroy(cfg);
516                 return AST_MODULE_LOAD_FAILURE;
517         }
518
519         /* Check for any aliases */
520         if (!reload) {
521                 /* Lock, if not already */
522                 AST_RWLIST_WRLOCK(&columns);
523         }
524         while ((entry = AST_LIST_REMOVE_HEAD(&columns, list))) {
525                 ast_free(entry);
526         }
527
528         ast_debug(1, "Got hostname of %s\n", ast_str_buffer(hostname));
529         ast_debug(1, "Got port of %d\n", dbport);
530         ast_debug(1, "Got a timeout of %d\n", timeout);
531         if (dbsock)
532                 ast_debug(1, "Got sock file of %s\n", ast_str_buffer(dbsock));
533         ast_debug(1, "Got user of %s\n", ast_str_buffer(dbuser));
534         ast_debug(1, "Got dbname of %s\n", ast_str_buffer(dbname));
535         ast_debug(1, "Got password of %s\n", ast_str_buffer(password));
536         ast_debug(1, "%sunning in calldate compatibility mode\n", calldate_compat ? "R" : "Not r");
537         ast_debug(1, "Dates and times are localized to %s\n", S_OR(ast_str_buffer(cdrzone), "local timezone"));
538
539         if (dbcharset) {
540                 ast_debug(1, "Got DB charset of %s\n", ast_str_buffer(dbcharset));
541         }
542
543         mysql_init(&mysql);
544
545         if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
546                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
547         }
548
549 #if MYSQL_VERSION_ID >= 50013
550         /* Add option for automatic reconnection */
551         if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
552                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
553         }
554 #endif
555
556         if ((ssl_ca && ast_str_strlen(ssl_ca)) || (ssl_cert && ast_str_strlen(ssl_cert)) || (ssl_key && ast_str_strlen(ssl_key))) {
557                 mysql_ssl_set(&mysql,
558                         ssl_key ? ast_str_buffer(ssl_key) : NULL,
559                         ssl_cert ? ast_str_buffer(ssl_cert) : NULL,
560                         ssl_ca ? ast_str_buffer(ssl_ca) : NULL,
561                         NULL, NULL);
562         }
563         temp = dbsock && ast_str_strlen(dbsock) ? ast_str_buffer(dbsock) : NULL;
564         if (!mysql_real_connect(&mysql, ast_str_buffer(hostname), ast_str_buffer(dbuser), ast_str_buffer(password), ast_str_buffer(dbname), dbport, temp, ssl_ca && ast_str_strlen(ssl_ca) ? CLIENT_SSL : 0)) {
565                 ast_log(LOG_ERROR, "Failed to connect to mysql database %s on %s.\n", ast_str_buffer(dbname), ast_str_buffer(hostname));
566                 connected = 0;
567                 records = 0;
568         } else {
569                 ast_debug(1, "Successfully connected to MySQL database.\n");
570                 connected = 1;
571                 records = 0;
572                 connect_time = time(NULL);
573                 if (dbcharset) {
574                         snprintf(sqldesc, sizeof(sqldesc), "SET NAMES '%s'", ast_str_buffer(dbcharset));
575                         mysql_real_query(&mysql, sqldesc, strlen(sqldesc));
576                         ast_debug(1, "SQL command as follows: %s\n", sqldesc);
577                 }
578
579                 /* Get table description */
580                 snprintf(sqldesc, sizeof(sqldesc), "DESC %s", dbtable ? ast_str_buffer(dbtable) : "cdr");
581                 if (mysql_query(&mysql, sqldesc)) {
582                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
583                         mysql_close(&mysql);
584                         connected = 0;
585                         AST_RWLIST_UNLOCK(&columns);
586                         ast_config_destroy(cfg);
587                         return AST_MODULE_LOAD_FAILURE;
588                 }
589
590                 if (!(result = mysql_store_result(&mysql))) {
591                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
592                         mysql_close(&mysql);
593                         connected = 0;
594                         AST_RWLIST_UNLOCK(&columns);
595                         ast_config_destroy(cfg);
596                         return AST_MODULE_LOAD_FAILURE;
597                 }
598
599                 while ((row = mysql_fetch_row(result))) {
600                         struct column *entry;
601                         char *cdrvar = "", *staticvalue = "";
602
603                         ast_debug(1, "Got a field '%s' of type '%s'\n", row[0], row[1]);
604                         /* Check for an alias or a static value */
605                         for (var = ast_variable_browse(cfg, "columns"); var; var = var->next) {
606                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, row[0]) == 0 ) {
607                                         char *alias = ast_strdupa(var->name + 5);
608                                         cdrvar = ast_strip(alias);
609                                         ast_verb(3, "Found alias %s for column %s\n", cdrvar, row[0]);
610                                         break;
611                                 } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, row[0]) == 0) {
612                                         char *item = ast_strdupa(var->name + 6);
613                                         item = ast_strip(item);
614                                         if (item[0] == '"' && item[strlen(item) - 1] == '"') {
615                                                 /* Remove surrounding quotes */
616                                                 item[strlen(item) - 1] = '\0';
617                                                 item++;
618                                         }
619                                         staticvalue = item;
620                                 }
621                         }
622
623                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(row[0]) + 1 + strlen(cdrvar) + 1 + strlen(staticvalue) + 1 + strlen(row[1]) + 1);
624                         if (!entry) {
625                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s'\n", row[0]);
626                                 res = -1;
627                                 break;
628                         }
629
630                         entry->name = (char *)entry + sizeof(*entry);
631                         strcpy(entry->name, row[0]);
632
633                         if (!ast_strlen_zero(cdrvar)) {
634                                 entry->cdrname = entry->name + strlen(row[0]) + 1;
635                                 strcpy(entry->cdrname, cdrvar);
636                         } else { /* Point to same place as the column name */
637                                 entry->cdrname = (char *)entry + sizeof(*entry);
638                         }
639
640                         if (!ast_strlen_zero(staticvalue)) {
641                                 entry->staticvalue = entry->cdrname + strlen(entry->cdrname) + 1;
642                                 strcpy(entry->staticvalue, staticvalue);
643                                 ast_debug(1, "staticvalue length: %d\n", (int) strlen(staticvalue) );
644                                 entry->type = entry->staticvalue + strlen(entry->staticvalue) + 1;
645                         } else {
646                                 entry->type = entry->cdrname + strlen(entry->cdrname) + 1;
647                         }
648                         strcpy(entry->type, row[1]);
649
650                         ast_debug(1, "Entry name '%s'\n", entry->name);
651                         ast_debug(1, "   cdrname '%s'\n", entry->cdrname);
652                         ast_debug(1, "    static '%s'\n", entry->staticvalue);
653                         ast_debug(1, "      type '%s'\n", entry->type);
654
655                         AST_LIST_INSERT_TAIL(&columns, entry, list);
656                 }
657                 mysql_free_result(result);
658         }
659         AST_RWLIST_UNLOCK(&columns);
660         ast_config_destroy(cfg);
661         if (res < 0) {
662                 return AST_MODULE_LOAD_FAILURE;
663         }
664
665         if (!reload) {
666                 res = ast_cdr_register(name, desc, mysql_log);
667         } else {
668                 res = ast_cdr_backend_unsuspend(name);
669         }
670         if (res) {
671                 ast_log(LOG_ERROR, "Unable to register MySQL CDR handling\n");
672         } else {
673                 res = ast_cli_register_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
674         }
675
676         return res;
677 }
678
679 static int load_module(void)
680 {
681         return my_load_module(0);
682 }
683
684 static int unload_module(void)
685 {
686         return my_unload_module(0);
687 }
688
689 static int reload(void)
690 {
691         int ret;
692
693         ast_mutex_lock(&mysql_lock);
694         ret = my_load_module(1);
695         ast_mutex_unlock(&mysql_lock);
696
697         return ret;
698 }
699
700 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "MySQL CDR Backend",
701         .support_level = AST_MODULE_SUPPORT_DEPRECATED,
702         .load = load_module,
703         .unload = unload_module,
704         .reload = reload,
705 );
706