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