Merged revisions 317837 via svnmerge from
[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 = { 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         /* Cannot use a conditionally different flag, because the table layout may
443          * have changed, which is not detectable by config file change detection,
444          * but should still cause the configuration to be re-parsed. */
445         cfg = ast_config_load(config, config_flags);
446         if (!cfg) {
447                 ast_log(LOG_WARNING, "Unable to load config for mysql CDR's: %s\n", config);
448                 return AST_MODULE_LOAD_SUCCESS;
449         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
450                 return AST_MODULE_LOAD_SUCCESS;
451
452         if (reload) {
453                 AST_RWLIST_WRLOCK(&columns);
454                 my_unload_module(1);
455         }
456
457         var = ast_variable_browse(cfg, "global");
458         if (!var) {
459                 /* nothing configured */
460                 if (reload) {
461                         AST_RWLIST_UNLOCK(&columns);
462                 }
463                 return AST_MODULE_LOAD_SUCCESS;
464         }
465
466         res = 0;
467
468         res |= my_load_config_string(cfg, "global", "hostname", &hostname, "localhost");
469         res |= my_load_config_string(cfg, "global", "dbname", &dbname, "astriskcdrdb");
470         res |= my_load_config_string(cfg, "global", "user", &dbuser, "root");
471         res |= my_load_config_string(cfg, "global", "sock", &dbsock, "");
472         res |= my_load_config_string(cfg, "global", "table", &dbtable, "cdr");
473         res |= my_load_config_string(cfg, "global", "password", &password, "");
474
475         res |= my_load_config_string(cfg, "global", "charset", &dbcharset, "");
476
477         res |= my_load_config_string(cfg, "global", "ssl_ca", &ssl_ca, "");
478         res |= my_load_config_string(cfg, "global", "ssl_cert", &ssl_cert, "");
479         res |= my_load_config_string(cfg, "global", "ssl_key", &ssl_key, "");
480
481         res |= my_load_config_number(cfg, "global", "port", &dbport, 0);
482         res |= my_load_config_number(cfg, "global", "timeout", &timeout, 0);
483         res |= my_load_config_string(cfg, "global", "compat", &compat, "no");
484         res |= my_load_config_string(cfg, "global", "cdrzone", &cdrzone, "");
485         if (ast_str_strlen(cdrzone) == 0) {
486                 for (; var; var = var->next) {
487                         if (!strcasecmp(var->name, "usegmtime") && ast_true(var->value)) {
488                                 ast_str_set(&cdrzone, 0, "UTC");
489                         }
490                 }
491         }
492
493         if (ast_true(ast_str_buffer(compat))) {
494                 calldate_compat = 1;
495         } else {
496                 calldate_compat = 0;
497         }
498
499         if (res < 0) {
500                 if (reload) {
501                         AST_RWLIST_UNLOCK(&columns);
502                 }
503                 return AST_MODULE_LOAD_FAILURE;
504         }
505
506         /* Check for any aliases */
507         if (!reload) {
508                 /* Lock, if not already */
509                 AST_RWLIST_WRLOCK(&columns);
510         }
511         while ((entry = AST_LIST_REMOVE_HEAD(&columns, list))) {
512                 ast_free(entry);
513         }
514
515         ast_debug(1, "Got hostname of %s\n", ast_str_buffer(hostname));
516         ast_debug(1, "Got port of %d\n", dbport);
517         ast_debug(1, "Got a timeout of %d\n", timeout);
518         if (dbsock)
519                 ast_debug(1, "Got sock file of %s\n", ast_str_buffer(dbsock));
520         ast_debug(1, "Got user of %s\n", ast_str_buffer(dbuser));
521         ast_debug(1, "Got dbname of %s\n", ast_str_buffer(dbname));
522         ast_debug(1, "Got password of %s\n", ast_str_buffer(password));
523         ast_debug(1, "%sunning in calldate compatibility mode\n", calldate_compat ? "R" : "Not r");
524         ast_debug(1, "Dates and times are localized to %s\n", S_OR(ast_str_buffer(cdrzone), "local timezone"));
525
526         if (dbcharset) {
527                 ast_debug(1, "Got DB charset of %s\n", ast_str_buffer(dbcharset));
528         }
529
530         mysql_init(&mysql);
531
532         if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
533                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
534         }
535
536 #if MYSQL_VERSION_ID >= 50013
537         /* Add option for automatic reconnection */
538         if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
539                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
540         }
541 #endif
542
543         if ((ssl_ca && ast_str_strlen(ssl_ca)) || (ssl_cert && ast_str_strlen(ssl_cert)) || (ssl_key && ast_str_strlen(ssl_key))) {
544                 mysql_ssl_set(&mysql,
545                         ssl_key ? ast_str_buffer(ssl_key) : NULL,
546                         ssl_cert ? ast_str_buffer(ssl_cert) : NULL,
547                         ssl_ca ? ast_str_buffer(ssl_ca) : NULL,
548                         NULL, NULL);
549         }
550         temp = dbsock && ast_str_strlen(dbsock) ? ast_str_buffer(dbsock) : NULL;
551         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)) {
552                 ast_log(LOG_ERROR, "Failed to connect to mysql database %s on %s.\n", ast_str_buffer(dbname), ast_str_buffer(hostname));
553                 connected = 0;
554                 records = 0;
555         } else {
556                 ast_debug(1, "Successfully connected to MySQL database.\n");
557                 connected = 1;
558                 records = 0;
559                 connect_time = time(NULL);
560                 if (dbcharset) {
561                         snprintf(sqldesc, sizeof(sqldesc), "SET NAMES '%s'", ast_str_buffer(dbcharset));
562                         mysql_real_query(&mysql, sqldesc, strlen(sqldesc));
563                         ast_debug(1, "SQL command as follows: %s\n", sqldesc);
564                 }
565
566                 /* Get table description */
567                 snprintf(sqldesc, sizeof(sqldesc), "DESC %s", dbtable ? ast_str_buffer(dbtable) : "cdr");
568                 if (mysql_query(&mysql, sqldesc)) {
569                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
570                         mysql_close(&mysql);
571                         connected = 0;
572                         AST_RWLIST_UNLOCK(&columns);
573                         ast_config_destroy(cfg);
574                         return AST_MODULE_LOAD_FAILURE;
575                 }
576
577                 if (!(result = mysql_store_result(&mysql))) {
578                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
579                         mysql_close(&mysql);
580                         connected = 0;
581                         AST_RWLIST_UNLOCK(&columns);
582                         ast_config_destroy(cfg);
583                         return AST_MODULE_LOAD_FAILURE;
584                 }
585
586                 while ((row = mysql_fetch_row(result))) {
587                         struct column *entry;
588                         char *cdrvar = "", *staticvalue = "";
589
590                         ast_debug(1, "Got a field '%s' of type '%s'\n", row[0], row[1]);
591                         /* Check for an alias or a static value */
592                         for (var = ast_variable_browse(cfg, "columns"); var; var = var->next) {
593                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, row[0]) == 0 ) {
594                                         char *alias = ast_strdupa(var->name + 5);
595                                         cdrvar = ast_strip(alias);
596                                         ast_verb(3, "Found alias %s for column %s\n", cdrvar, row[0]);
597                                         break;
598                                 } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, row[0]) == 0) {
599                                         char *item = ast_strdupa(var->name + 6);
600                                         item = ast_strip(item);
601                                         if (item[0] == '"' && item[strlen(item) - 1] == '"') {
602                                                 /* Remove surrounding quotes */
603                                                 item[strlen(item) - 1] = '\0';
604                                                 item++;
605                                         }
606                                         staticvalue = item;
607                                 }
608                         }
609
610                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(row[0]) + 1 + strlen(cdrvar) + 1 + strlen(staticvalue) + 1 + strlen(row[1]) + 1);
611                         if (!entry) {
612                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s'\n", row[0]);
613                                 res = -1;
614                                 break;
615                         }
616
617                         entry->name = (char *)entry + sizeof(*entry);
618                         strcpy(entry->name, row[0]);
619
620                         if (!ast_strlen_zero(cdrvar)) {
621                                 entry->cdrname = entry->name + strlen(row[0]) + 1;
622                                 strcpy(entry->cdrname, cdrvar);
623                         } else { /* Point to same place as the column name */
624                                 entry->cdrname = (char *)entry + sizeof(*entry);
625                         }
626
627                         if (!ast_strlen_zero(staticvalue)) {
628                                 entry->staticvalue = entry->cdrname + strlen(entry->cdrname) + 1;
629                                 strcpy(entry->staticvalue, staticvalue);
630                                 ast_debug(1, "staticvalue length: %d\n", (int) strlen(staticvalue) );
631                                 entry->type = entry->staticvalue + strlen(entry->staticvalue) + 1;
632                         } else {
633                                 entry->type = entry->cdrname + strlen(entry->cdrname) + 1;
634                         }
635                         strcpy(entry->type, row[1]);
636
637                         ast_debug(1, "Entry name '%s'\n", entry->name);
638                         ast_debug(1, "   cdrname '%s'\n", entry->cdrname);
639                         ast_debug(1, "    static '%s'\n", entry->staticvalue);
640                         ast_debug(1, "      type '%s'\n", entry->type);
641
642                         AST_LIST_INSERT_TAIL(&columns, entry, list);
643                 }
644                 mysql_free_result(result);
645         }
646         AST_RWLIST_UNLOCK(&columns);
647         ast_config_destroy(cfg);
648         if (res < 0) {
649                 return AST_MODULE_LOAD_FAILURE;
650         }
651
652         res = ast_cdr_register(name, desc, mysql_log);
653         if (res) {
654                 ast_log(LOG_ERROR, "Unable to register MySQL CDR handling\n");
655         } else {
656                 res = ast_cli_register_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
657         }
658
659         return res;
660 }
661
662 static int load_module(void)
663 {
664         return my_load_module(0);
665 }
666
667 static int unload_module(void)
668 {
669         return my_unload_module(0);
670 }
671
672 static int reload(void)
673 {
674         int ret;
675
676         ast_mutex_lock(&mysql_lock);
677         ret = my_load_module(1);
678         ast_mutex_unlock(&mysql_lock);
679
680         return ret;
681 }
682
683 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "MySQL CDR Backend",
684         .load = load_module,
685         .unload = unload_module,
686         .reload = reload,
687 );
688