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