Merge "res_pjsip: Avoid crash when contact uri is empty string"
[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 #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];
121                 char status2[100] = "";
122                 char buf[362]; /* 256+100+" for "+NULL */
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
136                 snprintf(buf, sizeof(buf), "%s%s for ", status, status2);
137                 ast_cli_print_timestr_fromseconds(a->fd, ctime, buf);
138
139                 if (records == totalrecords)
140                         ast_cli(a->fd, "  Wrote %d records since last restart.\n", totalrecords);
141                 else
142                         ast_cli(a->fd, "  Wrote %d records since last restart and %d records since last reconnect.\n", totalrecords, records);
143         } else {
144                 ast_cli(a->fd, "Not currently connected to a MySQL server.\n");
145         }
146
147         return CLI_SUCCESS;
148 }
149
150 static struct ast_cli_entry cdr_mysql_status_cli[] = {
151         AST_CLI_DEFINE(handle_cli_cdr_mysql_status, "Show connection status of cdr_mysql"),
152 };
153
154 static int mysql_log(struct ast_cdr *cdr)
155 {
156         struct ast_str *sql1 = ast_str_thread_get(&sql1_buf, 1024), *sql2 = ast_str_thread_get(&sql2_buf, 1024);
157         int retries = 5;
158 #if MYSQL_VERSION_ID >= 50013
159         my_bool my_bool_true = 1;
160 #endif
161
162         if (!sql1 || !sql2) {
163                 ast_log(LOG_ERROR, "Memory error\n");
164                 return -1;
165         }
166
167         ast_mutex_lock(&mysql_lock);
168
169 db_reconnect:
170         if ((!connected) && (hostname || dbsock) && dbuser && password && dbname && dbtable ) {
171                 /* Attempt to connect */
172                 mysql_init(&mysql);
173                 /* Add option to quickly timeout the connection */
174                 if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
175                         ast_log(LOG_ERROR, "mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
176                 }
177 #if MYSQL_VERSION_ID >= 50013
178                 /* Add option for automatic reconnection */
179                 if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
180                         ast_log(LOG_ERROR, "mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
181                 }
182 #endif
183                 if (ssl_ca || ssl_cert || ssl_key) {
184                         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);
185                 }
186                 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)) {
187                         connected = 1;
188                         connect_time = time(NULL);
189                         records = 0;
190                         if (dbcharset) {
191                                 ast_str_set(&sql1, 0, "SET NAMES '%s'", ast_str_buffer(dbcharset));
192                                 mysql_real_query(&mysql, ast_str_buffer(sql1), ast_str_strlen(sql1));
193                                 ast_debug(1, "SQL command as follows: %s\n", ast_str_buffer(sql1));
194                         }
195                 } else {
196                         ast_log(LOG_ERROR, "Cannot connect to database server %s: (%d) %s\n", ast_str_buffer(hostname), mysql_errno(&mysql), mysql_error(&mysql));
197                         connected = 0;
198                 }
199         } else {
200                 /* Long connection - ping the server */
201                 int error;
202                 if ((error = mysql_ping(&mysql))) {
203                         connected = 0;
204                         records = 0;
205                         switch (mysql_errno(&mysql)) {
206                                 case CR_SERVER_GONE_ERROR:
207                                 case CR_SERVER_LOST:
208                                         ast_log(LOG_ERROR, "Server has gone away. Attempting to reconnect.\n");
209                                         break;
210                                 default:
211                                         ast_log(LOG_ERROR, "Unknown connection error: (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
212                         }
213                         retries--;
214                         if (retries) {
215                                 goto db_reconnect;
216                         } else {
217                                 ast_log(LOG_ERROR, "Retried to connect five times, giving up.\n");
218                         }
219                 }
220         }
221
222         if (connected) {
223                 int column_count = 0;
224                 char *cdrname;
225                 char workspace[2048], *value = NULL;
226                 struct column *entry;
227                 struct ast_str *escape = ast_str_thread_get(&escape_buf, 16);
228
229                 ast_str_set(&sql1, 0, "INSERT INTO %s (", AS_OR(dbtable, "cdr"));
230                 ast_str_set(&sql2, 0, ") VALUES (");
231
232                 AST_RWLIST_RDLOCK(&columns);
233                 AST_RWLIST_TRAVERSE(&columns, entry, list) {
234                         if (!strcmp(entry->name, "calldate")) {
235                                 /*!\note
236                                  * For some dumb reason, "calldate" used to be formulated using
237                                  * the datetime the record was posted, rather than the start
238                                  * time of the call.  If someone really wants the old compatible
239                                  * behavior, it's provided here.
240                                  */
241                                 if (calldate_compat) {
242                                         struct timeval tv = ast_tvnow();
243                                         struct ast_tm tm;
244                                         char timestr[128];
245                                         ast_localtime(&tv, &tm, ast_str_strlen(cdrzone) ? ast_str_buffer(cdrzone) : NULL);
246                                         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
247                                         value = ast_strdupa(timestr);
248                                         cdrname = "calldate";
249                                 } else {
250                                         cdrname = "start";
251                                 }
252                         } else {
253                                 cdrname = entry->cdrname;
254                         }
255
256                         /* Construct SQL */
257
258                         /* Need the type and value to determine if we want the raw value or not */
259                         if (entry->staticvalue) {
260                                 value = ast_strdupa(entry->staticvalue);
261                         } else if ((!strcmp(cdrname, "disposition") ||
262                                  !strcmp(cdrname, "amaflags")) &&
263                                 (strstr(entry->type, "int") ||
264                                  strstr(entry->type, "dec") ||
265                                  strstr(entry->type, "float") ||
266                                  strstr(entry->type, "double") ||
267                                  strstr(entry->type, "real") ||
268                                  strstr(entry->type, "numeric") ||
269                                  strstr(entry->type, "fixed"))) {
270                                 ast_cdr_format_var(cdr, cdrname, &value, workspace, sizeof(workspace), 1);
271                         } else if (!strcmp(cdrname, "start") || !strcmp(cdrname, "answer") ||
272                                  !strcmp(cdrname, "end")) {
273                                 struct ast_tm tm;
274                                 char timestr[128];
275                                 ast_localtime(&cdr->start, &tm, ast_str_strlen(cdrzone) ? ast_str_buffer(cdrzone) : NULL);
276                                 ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
277                                 value = ast_strdupa(timestr);
278                         } else if (!strcmp(cdrname, "calldate")) {
279                                 /* Skip calldate - the value has already been dup'd */
280                         } else {
281                                 ast_cdr_format_var(cdr, cdrname, &value, workspace, sizeof(workspace), 0);
282                         }
283
284                         if (value) {
285                                 size_t valsz;
286
287                                 if (column_count++) {
288                                         ast_str_append(&sql1, 0, ",");
289                                         ast_str_append(&sql2, 0, ",");
290                                 }
291
292                                 if (!strcasecmp(cdrname, "billsec") &&
293                                         (strstr(entry->type, "float") ||
294                                         strstr(entry->type, "double") ||
295                                         strstr(entry->type, "decimal") ||
296                                         strstr(entry->type, "numeric") ||
297                                         strstr(entry->type, "real"))) {
298
299                                         if (!ast_tvzero(cdr->answer)) {
300                                                 snprintf(workspace, sizeof(workspace), "%lf",
301                                                         (double) (ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0));
302                                         } else {
303                                                 ast_copy_string(workspace, "0", sizeof(workspace));
304                                         }
305
306                                         if (!ast_strlen_zero(workspace)) {
307                                                 value = workspace;
308                                         }
309                                 }
310
311                                 if (!strcasecmp(cdrname, "duration") &&
312                                         (strstr(entry->type, "float") ||
313                                         strstr(entry->type, "double") ||
314                                         strstr(entry->type, "decimal") ||
315                                         strstr(entry->type, "numeric") ||
316                                         strstr(entry->type, "real"))) {
317
318                                         snprintf(workspace, sizeof(workspace), "%lf",
319                                                 (double) (ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0));
320
321                                         if (!ast_strlen_zero(workspace)) {
322                                                 value = workspace;
323                                         }
324                                 }
325
326                                 ast_str_make_space(&escape, (valsz = strlen(value)) * 2 + 1);
327                                 mysql_real_escape_string(&mysql, ast_str_buffer(escape), value, valsz);
328
329                                 ast_str_append(&sql1, 0, "`%s`", entry->name);
330                                 ast_str_append(&sql2, 0, "'%s'", ast_str_buffer(escape));
331                         }
332                 }
333                 AST_RWLIST_UNLOCK(&columns);
334
335                 ast_debug(1, "Inserting a CDR record.\n");
336                 ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
337
338                 ast_debug(1, "SQL command as follows: %s\n", ast_str_buffer(sql1));
339
340                 if (mysql_real_query(&mysql, ast_str_buffer(sql1), ast_str_strlen(sql1))) {
341                         ast_log(LOG_ERROR, "Failed to insert into database: (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
342                         mysql_close(&mysql);
343                         connected = 0;
344                 } else {
345                         records++;
346                         totalrecords++;
347                 }
348         }
349         ast_mutex_unlock(&mysql_lock);
350         return 0;
351 }
352
353 static void free_strings(void)
354 {
355         struct unload_string *us;
356
357         AST_LIST_LOCK(&unload_strings);
358         while ((us = AST_LIST_REMOVE_HEAD(&unload_strings, entry))) {
359                 ast_free(us->str);
360                 ast_free(us);
361         }
362         AST_LIST_UNLOCK(&unload_strings);
363 }
364
365 static int my_unload_module(int reload)
366 {
367         struct column *entry;
368
369         ast_cli_unregister_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
370
371         if (connected) {
372                 mysql_close(&mysql);
373                 connected = 0;
374                 records = 0;
375         }
376
377         free_strings();
378
379         if (!reload) {
380                 AST_RWLIST_WRLOCK(&columns);
381         }
382         while ((entry = AST_RWLIST_REMOVE_HEAD(&columns, list))) {
383                 ast_free(entry);
384         }
385         if (!reload) {
386                 AST_RWLIST_UNLOCK(&columns);
387         }
388
389         dbport = 0;
390         if (reload) {
391                 return ast_cdr_backend_suspend(name);
392         } else {
393                 return ast_cdr_unregister(name);
394         }
395 }
396
397 static int my_load_config_string(struct ast_config *cfg, const char *category, const char *variable, struct ast_str **field, const char *def)
398 {
399         struct unload_string *us;
400         const char *tmp;
401
402         if (!(us = ast_calloc(1, sizeof(*us))))
403                 return -1;
404
405         if (!(*field = ast_str_create(16))) {
406                 ast_free(us);
407                 return -1;
408         }
409
410         tmp = ast_variable_retrieve(cfg, category, variable);
411
412         ast_str_set(field, 0, "%s", tmp ? tmp : def);
413
414         us->str = *field;
415
416         AST_LIST_LOCK(&unload_strings);
417         AST_LIST_INSERT_HEAD(&unload_strings, us, entry);
418         AST_LIST_UNLOCK(&unload_strings);
419
420         return 0;
421 }
422
423 static int my_load_config_number(struct ast_config *cfg, const char *category, const char *variable, int *field, int def)
424 {
425         const char *tmp;
426
427         tmp = ast_variable_retrieve(cfg, category, variable);
428
429         if (!tmp || sscanf(tmp, "%30d", field) < 1)
430                 *field = def;
431
432         return 0;
433 }
434
435 static int my_load_module(int reload)
436 {
437         int res;
438         struct ast_config *cfg;
439         struct ast_variable *var;
440         /* CONFIG_STATUS_FILEUNCHANGED is impossible when config_flags is always 0,
441          * and it has to be zero, so a reload can be sent to tell the driver to
442          * rescan the table layout. */
443         struct ast_flags config_flags = { 0 };
444         struct column *entry;
445         char *temp;
446         struct ast_str *compat;
447         MYSQL_ROW row;
448         MYSQL_RES *result;
449         char sqldesc[128];
450 #if MYSQL_VERSION_ID >= 50013
451         my_bool my_bool_true = 1;
452 #endif
453
454         /* Cannot use a conditionally different flag, because the table layout may
455          * have changed, which is not detectable by config file change detection,
456          * but should still cause the configuration to be re-parsed. */
457         cfg = ast_config_load(config, config_flags);
458         if (cfg == CONFIG_STATUS_FILEMISSING) {
459                 ast_log(LOG_WARNING, "Unable to load config for mysql CDR's: %s\n", config);
460                 return AST_MODULE_LOAD_SUCCESS;
461         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
462                 ast_log(LOG_ERROR, "Unable to load configuration file '%s'\n", config);
463                 return AST_MODULE_LOAD_DECLINE;
464         }
465
466         if (reload) {
467                 AST_RWLIST_WRLOCK(&columns);
468                 my_unload_module(1);
469         }
470
471         var = ast_variable_browse(cfg, "global");
472         if (!var) {
473                 /* nothing configured */
474                 if (reload) {
475                         AST_RWLIST_UNLOCK(&columns);
476                 }
477                 ast_config_destroy(cfg);
478                 return AST_MODULE_LOAD_SUCCESS;
479         }
480
481         res = 0;
482
483         res |= my_load_config_string(cfg, "global", "hostname", &hostname, "localhost");
484         res |= my_load_config_string(cfg, "global", "dbname", &dbname, "astriskcdrdb");
485         res |= my_load_config_string(cfg, "global", "user", &dbuser, "root");
486         res |= my_load_config_string(cfg, "global", "sock", &dbsock, "");
487         res |= my_load_config_string(cfg, "global", "table", &dbtable, "cdr");
488         res |= my_load_config_string(cfg, "global", "password", &password, "");
489
490         res |= my_load_config_string(cfg, "global", "charset", &dbcharset, "");
491
492         res |= my_load_config_string(cfg, "global", "ssl_ca", &ssl_ca, "");
493         res |= my_load_config_string(cfg, "global", "ssl_cert", &ssl_cert, "");
494         res |= my_load_config_string(cfg, "global", "ssl_key", &ssl_key, "");
495
496         res |= my_load_config_number(cfg, "global", "port", &dbport, 0);
497         res |= my_load_config_number(cfg, "global", "timeout", &timeout, 0);
498         res |= my_load_config_string(cfg, "global", "compat", &compat, "no");
499         res |= my_load_config_string(cfg, "global", "cdrzone", &cdrzone, "");
500         if (ast_str_strlen(cdrzone) == 0) {
501                 for (; var; var = var->next) {
502                         if (!strcasecmp(var->name, "usegmtime") && ast_true(var->value)) {
503                                 ast_str_set(&cdrzone, 0, "UTC");
504                         }
505                 }
506         }
507
508         if (ast_true(ast_str_buffer(compat))) {
509                 calldate_compat = 1;
510         } else {
511                 calldate_compat = 0;
512         }
513
514         if (res < 0) {
515                 if (reload) {
516                         AST_RWLIST_UNLOCK(&columns);
517                 }
518                 ast_config_destroy(cfg);
519                 free_strings();
520
521                 return AST_MODULE_LOAD_DECLINE;
522         }
523
524         /* Check for any aliases */
525         if (!reload) {
526                 /* Lock, if not already */
527                 AST_RWLIST_WRLOCK(&columns);
528         }
529         while ((entry = AST_LIST_REMOVE_HEAD(&columns, list))) {
530                 ast_free(entry);
531         }
532
533         ast_debug(1, "Got hostname of %s\n", ast_str_buffer(hostname));
534         ast_debug(1, "Got port of %d\n", dbport);
535         ast_debug(1, "Got a timeout of %d\n", timeout);
536         if (dbsock)
537                 ast_debug(1, "Got sock file of %s\n", ast_str_buffer(dbsock));
538         ast_debug(1, "Got user of %s\n", ast_str_buffer(dbuser));
539         ast_debug(1, "Got dbname of %s\n", ast_str_buffer(dbname));
540         ast_debug(1, "Got password of %s\n", ast_str_buffer(password));
541         ast_debug(1, "%sunning in calldate compatibility mode\n", calldate_compat ? "R" : "Not r");
542         ast_debug(1, "Dates and times are localized to %s\n", S_OR(ast_str_buffer(cdrzone), "local timezone"));
543
544         if (dbcharset) {
545                 ast_debug(1, "Got DB charset of %s\n", ast_str_buffer(dbcharset));
546         }
547
548         mysql_init(&mysql);
549
550         if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
551                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
552         }
553
554 #if MYSQL_VERSION_ID >= 50013
555         /* Add option for automatic reconnection */
556         if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
557                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
558         }
559 #endif
560
561         if ((ssl_ca && ast_str_strlen(ssl_ca)) || (ssl_cert && ast_str_strlen(ssl_cert)) || (ssl_key && ast_str_strlen(ssl_key))) {
562                 mysql_ssl_set(&mysql,
563                         ssl_key ? ast_str_buffer(ssl_key) : NULL,
564                         ssl_cert ? ast_str_buffer(ssl_cert) : NULL,
565                         ssl_ca ? ast_str_buffer(ssl_ca) : NULL,
566                         NULL, NULL);
567         }
568         temp = dbsock && ast_str_strlen(dbsock) ? ast_str_buffer(dbsock) : NULL;
569         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)) {
570                 ast_log(LOG_ERROR, "Failed to connect to mysql database %s on %s.\n", ast_str_buffer(dbname), ast_str_buffer(hostname));
571                 connected = 0;
572                 records = 0;
573         } else {
574                 ast_debug(1, "Successfully connected to MySQL database.\n");
575                 connected = 1;
576                 records = 0;
577                 connect_time = time(NULL);
578                 if (dbcharset) {
579                         snprintf(sqldesc, sizeof(sqldesc), "SET NAMES '%s'", ast_str_buffer(dbcharset));
580                         mysql_real_query(&mysql, sqldesc, strlen(sqldesc));
581                         ast_debug(1, "SQL command as follows: %s\n", sqldesc);
582                 }
583
584                 /* Get table description */
585                 snprintf(sqldesc, sizeof(sqldesc), "DESC %s", dbtable ? ast_str_buffer(dbtable) : "cdr");
586                 if (mysql_query(&mysql, sqldesc)) {
587                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
588                         mysql_close(&mysql);
589                         connected = 0;
590                         AST_RWLIST_UNLOCK(&columns);
591                         ast_config_destroy(cfg);
592                         free_strings();
593
594                         return AST_MODULE_LOAD_DECLINE;
595                 }
596
597                 if (!(result = mysql_store_result(&mysql))) {
598                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
599                         mysql_close(&mysql);
600                         connected = 0;
601                         AST_RWLIST_UNLOCK(&columns);
602                         ast_config_destroy(cfg);
603                         free_strings();
604
605                         return AST_MODULE_LOAD_DECLINE;
606                 }
607
608                 while ((row = mysql_fetch_row(result))) {
609                         struct column *entry;
610                         char *cdrvar = "", *staticvalue = "";
611
612                         ast_debug(1, "Got a field '%s' of type '%s'\n", row[0], row[1]);
613                         /* Check for an alias or a static value */
614                         for (var = ast_variable_browse(cfg, "columns"); var; var = var->next) {
615                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, row[0]) == 0 ) {
616                                         char *alias = ast_strdupa(var->name + 5);
617                                         cdrvar = ast_strip(alias);
618                                         ast_verb(3, "Found alias %s for column %s\n", cdrvar, row[0]);
619                                         break;
620                                 } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, row[0]) == 0) {
621                                         char *item = ast_strdupa(var->name + 6);
622                                         item = ast_strip(item);
623                                         if (item[0] == '"' && item[strlen(item) - 1] == '"') {
624                                                 /* Remove surrounding quotes */
625                                                 item[strlen(item) - 1] = '\0';
626                                                 item++;
627                                         }
628                                         staticvalue = item;
629                                 }
630                         }
631
632                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(row[0]) + 1 + strlen(cdrvar) + 1 + strlen(staticvalue) + 1 + strlen(row[1]) + 1);
633                         if (!entry) {
634                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s'\n", row[0]);
635                                 res = -1;
636                                 break;
637                         }
638
639                         entry->name = (char *)entry + sizeof(*entry);
640                         strcpy(entry->name, row[0]);
641
642                         if (!ast_strlen_zero(cdrvar)) {
643                                 entry->cdrname = entry->name + strlen(row[0]) + 1;
644                                 strcpy(entry->cdrname, cdrvar);
645                         } else { /* Point to same place as the column name */
646                                 entry->cdrname = (char *)entry + sizeof(*entry);
647                         }
648
649                         if (!ast_strlen_zero(staticvalue)) {
650                                 entry->staticvalue = entry->cdrname + strlen(entry->cdrname) + 1;
651                                 strcpy(entry->staticvalue, staticvalue);
652                                 ast_debug(1, "staticvalue length: %d\n", (int) strlen(staticvalue) );
653                                 entry->type = entry->staticvalue + strlen(entry->staticvalue) + 1;
654                         } else {
655                                 entry->type = entry->cdrname + strlen(entry->cdrname) + 1;
656                         }
657                         strcpy(entry->type, row[1]);
658
659                         ast_debug(1, "Entry name '%s'\n", entry->name);
660                         ast_debug(1, "   cdrname '%s'\n", entry->cdrname);
661                         ast_debug(1, "    static '%s'\n", entry->staticvalue);
662                         ast_debug(1, "      type '%s'\n", entry->type);
663
664                         AST_LIST_INSERT_TAIL(&columns, entry, list);
665                 }
666                 mysql_free_result(result);
667         }
668         AST_RWLIST_UNLOCK(&columns);
669         ast_config_destroy(cfg);
670         if (res < 0) {
671                 my_unload_module(0);
672                 return AST_MODULE_LOAD_DECLINE;
673         }
674
675         if (!reload) {
676                 res = ast_cdr_register(name, desc, mysql_log);
677         } else {
678                 res = ast_cdr_backend_unsuspend(name);
679         }
680         if (res) {
681                 ast_log(LOG_ERROR, "Unable to register MySQL CDR handling\n");
682         } else {
683                 res = ast_cli_register_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
684         }
685
686         if (res) {
687                 my_unload_module(0);
688                 return AST_MODULE_LOAD_DECLINE;
689         }
690
691         return AST_MODULE_LOAD_SUCCESS;
692 }
693
694 static int load_module(void)
695 {
696         return my_load_module(0);
697 }
698
699 static int unload_module(void)
700 {
701         return my_unload_module(0);
702 }
703
704 static int reload(void)
705 {
706         int ret;
707
708         ast_mutex_lock(&mysql_lock);
709         ret = my_load_module(1);
710         ast_mutex_unlock(&mysql_lock);
711
712         return ret;
713 }
714
715 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "MySQL CDR Backend",
716         .support_level = AST_MODULE_SUPPORT_DEPRECATED,
717         .load = load_module,
718         .unload = unload_module,
719         .reload = reload,
720 );
721