Merged revisions 338995 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         <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                                         ast_cdr_setvar(cdr, "calldate", timestr, 0);
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_getvar(cdr, cdrname, &value, workspace, sizeof(workspace), 0, 1);
281                         } else {
282                                 ast_cdr_getvar(cdr, cdrname, &value, workspace, sizeof(workspace), 0, 0);
283                         }
284
285                         if (value) {
286                                 size_t valsz;
287
288                                 if (column_count++) {
289                                         ast_str_append(&sql1, 0, ",");
290                                         ast_str_append(&sql2, 0, ",");
291                                 }
292
293                                 if (!strcasecmp(cdrname, "billsec") &&
294                                         (strstr(entry->type, "float") ||
295                                         strstr(entry->type, "double") ||
296                                         strstr(entry->type, "decimal") ||
297                                         strstr(entry->type, "numeric") ||
298                                         strstr(entry->type, "real"))) {
299
300                                         if (!ast_tvzero(cdr->answer)) {
301                                                 snprintf(workspace, sizeof(workspace), "%lf",
302                                                         (double) (ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0));
303                                         } else {
304                                                 ast_copy_string(workspace, "0", sizeof(workspace));
305                                         }
306
307                                         if (!ast_strlen_zero(workspace)) {
308                                                 value = workspace;
309                                         }
310                                 }
311
312                                 if (!strcasecmp(cdrname, "duration") &&
313                                         (strstr(entry->type, "float") ||
314                                         strstr(entry->type, "double") ||
315                                         strstr(entry->type, "decimal") ||
316                                         strstr(entry->type, "numeric") ||
317                                         strstr(entry->type, "real"))) {
318
319                                         snprintf(workspace, sizeof(workspace), "%lf",
320                                                 (double) (ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0));
321
322                                         if (!ast_strlen_zero(workspace)) {
323                                                 value = workspace;
324                                         }
325                                 }
326
327                                 ast_str_make_space(&escape, (valsz = strlen(value)) * 2 + 1);
328                                 mysql_real_escape_string(&mysql, ast_str_buffer(escape), value, valsz);
329
330                                 ast_str_append(&sql1, 0, "`%s`", entry->name);
331                                 ast_str_append(&sql2, 0, "'%s'", ast_str_buffer(escape));
332                         }
333                 }
334                 AST_RWLIST_UNLOCK(&columns);
335
336                 ast_debug(1, "Inserting a CDR record.\n");
337                 ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
338
339                 ast_debug(1, "SQL command as follows: %s\n", ast_str_buffer(sql1));
340
341                 if (mysql_real_query(&mysql, ast_str_buffer(sql1), ast_str_strlen(sql1))) {
342                         ast_log(LOG_ERROR, "Failed to insert into database: (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
343                         mysql_close(&mysql);
344                         connected = 0;
345                 } else {
346                         records++;
347                         totalrecords++;
348                 }
349         }
350         ast_mutex_unlock(&mysql_lock);
351         return 0;
352 }
353
354 static int my_unload_module(int reload)
355
356         struct unload_string *us;
357         struct column *entry;
358
359         ast_cli_unregister_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
360
361         if (connected) {
362                 mysql_close(&mysql);
363                 connected = 0;
364                 records = 0;
365         }
366
367         AST_LIST_LOCK(&unload_strings);
368         while ((us = AST_LIST_REMOVE_HEAD(&unload_strings, entry))) {
369                 ast_free(us->str);
370                 ast_free(us);
371         }
372         AST_LIST_UNLOCK(&unload_strings);
373
374         if (!reload) {
375                 AST_RWLIST_WRLOCK(&columns);
376         }
377         while ((entry = AST_RWLIST_REMOVE_HEAD(&columns, list))) {
378                 ast_free(entry);
379         }
380         if (!reload) {
381                 AST_RWLIST_UNLOCK(&columns);
382         }
383
384         dbport = 0;
385         ast_cdr_unregister(name);
386         
387         return 0;
388 }
389
390 static int my_load_config_string(struct ast_config *cfg, const char *category, const char *variable, struct ast_str **field, const char *def)
391 {
392         struct unload_string *us;
393         const char *tmp;
394
395         if (!(us = ast_calloc(1, sizeof(*us))))
396                 return -1;
397
398         if (!(*field = ast_str_create(16))) {
399                 ast_free(us);
400                 return -1;
401         }
402
403         tmp = ast_variable_retrieve(cfg, category, variable);
404
405         ast_str_set(field, 0, "%s", tmp ? tmp : def);
406
407         us->str = *field;
408
409         AST_LIST_LOCK(&unload_strings);
410         AST_LIST_INSERT_HEAD(&unload_strings, us, entry);
411         AST_LIST_UNLOCK(&unload_strings);
412
413         return 0;
414 }
415
416 static int my_load_config_number(struct ast_config *cfg, const char *category, const char *variable, int *field, int def)
417 {
418         const char *tmp;
419
420         tmp = ast_variable_retrieve(cfg, category, variable);
421
422         if (!tmp || sscanf(tmp, "%30d", field) < 1)
423                 *field = def;
424
425         return 0;
426 }
427
428 static int my_load_module(int reload)
429 {
430         int res;
431         struct ast_config *cfg;
432         struct ast_variable *var;
433         struct ast_flags config_flags = { 0 };
434         struct column *entry;
435         char *temp;
436         struct ast_str *compat;
437         MYSQL_ROW row;
438         MYSQL_RES *result;
439         char sqldesc[128];
440 #if MYSQL_VERSION_ID >= 50013
441         my_bool my_bool_true = 1;
442 #endif
443
444         /* Cannot use a conditionally different flag, because the table layout may
445          * have changed, which is not detectable by config file change detection,
446          * but should still cause the configuration to be re-parsed. */
447         cfg = ast_config_load(config, config_flags);
448         if (!cfg) {
449                 ast_log(LOG_WARNING, "Unable to load config for mysql CDR's: %s\n", config);
450                 return AST_MODULE_LOAD_SUCCESS;
451         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
452                 return AST_MODULE_LOAD_SUCCESS;
453
454         if (reload) {
455                 AST_RWLIST_WRLOCK(&columns);
456                 my_unload_module(1);
457         }
458
459         var = ast_variable_browse(cfg, "global");
460         if (!var) {
461                 /* nothing configured */
462                 if (reload) {
463                         AST_RWLIST_UNLOCK(&columns);
464                 }
465                 return AST_MODULE_LOAD_SUCCESS;
466         }
467
468         res = 0;
469
470         res |= my_load_config_string(cfg, "global", "hostname", &hostname, "localhost");
471         res |= my_load_config_string(cfg, "global", "dbname", &dbname, "astriskcdrdb");
472         res |= my_load_config_string(cfg, "global", "user", &dbuser, "root");
473         res |= my_load_config_string(cfg, "global", "sock", &dbsock, "");
474         res |= my_load_config_string(cfg, "global", "table", &dbtable, "cdr");
475         res |= my_load_config_string(cfg, "global", "password", &password, "");
476
477         res |= my_load_config_string(cfg, "global", "charset", &dbcharset, "");
478
479         res |= my_load_config_string(cfg, "global", "ssl_ca", &ssl_ca, "");
480         res |= my_load_config_string(cfg, "global", "ssl_cert", &ssl_cert, "");
481         res |= my_load_config_string(cfg, "global", "ssl_key", &ssl_key, "");
482
483         res |= my_load_config_number(cfg, "global", "port", &dbport, 0);
484         res |= my_load_config_number(cfg, "global", "timeout", &timeout, 0);
485         res |= my_load_config_string(cfg, "global", "compat", &compat, "no");
486         res |= my_load_config_string(cfg, "global", "cdrzone", &cdrzone, "");
487         if (ast_str_strlen(cdrzone) == 0) {
488                 for (; var; var = var->next) {
489                         if (!strcasecmp(var->name, "usegmtime") && ast_true(var->value)) {
490                                 ast_str_set(&cdrzone, 0, "UTC");
491                         }
492                 }
493         }
494
495         if (ast_true(ast_str_buffer(compat))) {
496                 calldate_compat = 1;
497         } else {
498                 calldate_compat = 0;
499         }
500
501         if (res < 0) {
502                 if (reload) {
503                         AST_RWLIST_UNLOCK(&columns);
504                 }
505                 return AST_MODULE_LOAD_FAILURE;
506         }
507
508         /* Check for any aliases */
509         if (!reload) {
510                 /* Lock, if not already */
511                 AST_RWLIST_WRLOCK(&columns);
512         }
513         while ((entry = AST_LIST_REMOVE_HEAD(&columns, list))) {
514                 ast_free(entry);
515         }
516
517         ast_debug(1, "Got hostname of %s\n", ast_str_buffer(hostname));
518         ast_debug(1, "Got port of %d\n", dbport);
519         ast_debug(1, "Got a timeout of %d\n", timeout);
520         if (dbsock)
521                 ast_debug(1, "Got sock file of %s\n", ast_str_buffer(dbsock));
522         ast_debug(1, "Got user of %s\n", ast_str_buffer(dbuser));
523         ast_debug(1, "Got dbname of %s\n", ast_str_buffer(dbname));
524         ast_debug(1, "Got password of %s\n", ast_str_buffer(password));
525         ast_debug(1, "%sunning in calldate compatibility mode\n", calldate_compat ? "R" : "Not r");
526         ast_debug(1, "Dates and times are localized to %s\n", S_OR(ast_str_buffer(cdrzone), "local timezone"));
527
528         if (dbcharset) {
529                 ast_debug(1, "Got DB charset of %s\n", ast_str_buffer(dbcharset));
530         }
531
532         mysql_init(&mysql);
533
534         if (timeout && mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout) != 0) {
535                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
536         }
537
538 #if MYSQL_VERSION_ID >= 50013
539         /* Add option for automatic reconnection */
540         if (mysql_options(&mysql, MYSQL_OPT_RECONNECT, &my_bool_true) != 0) {
541                 ast_log(LOG_ERROR, "cdr_mysql: mysql_options returned (%d) %s\n", mysql_errno(&mysql), mysql_error(&mysql));
542         }
543 #endif
544
545         if ((ssl_ca && ast_str_strlen(ssl_ca)) || (ssl_cert && ast_str_strlen(ssl_cert)) || (ssl_key && ast_str_strlen(ssl_key))) {
546                 mysql_ssl_set(&mysql,
547                         ssl_key ? ast_str_buffer(ssl_key) : NULL,
548                         ssl_cert ? ast_str_buffer(ssl_cert) : NULL,
549                         ssl_ca ? ast_str_buffer(ssl_ca) : NULL,
550                         NULL, NULL);
551         }
552         temp = dbsock && ast_str_strlen(dbsock) ? ast_str_buffer(dbsock) : NULL;
553         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)) {
554                 ast_log(LOG_ERROR, "Failed to connect to mysql database %s on %s.\n", ast_str_buffer(dbname), ast_str_buffer(hostname));
555                 connected = 0;
556                 records = 0;
557         } else {
558                 ast_debug(1, "Successfully connected to MySQL database.\n");
559                 connected = 1;
560                 records = 0;
561                 connect_time = time(NULL);
562                 if (dbcharset) {
563                         snprintf(sqldesc, sizeof(sqldesc), "SET NAMES '%s'", ast_str_buffer(dbcharset));
564                         mysql_real_query(&mysql, sqldesc, strlen(sqldesc));
565                         ast_debug(1, "SQL command as follows: %s\n", sqldesc);
566                 }
567
568                 /* Get table description */
569                 snprintf(sqldesc, sizeof(sqldesc), "DESC %s", dbtable ? ast_str_buffer(dbtable) : "cdr");
570                 if (mysql_query(&mysql, sqldesc)) {
571                         ast_log(LOG_ERROR, "Unable to query table description!!  Logging disabled.\n");
572                         mysql_close(&mysql);
573                         connected = 0;
574                         AST_RWLIST_UNLOCK(&columns);
575                         ast_config_destroy(cfg);
576                         return AST_MODULE_LOAD_FAILURE;
577                 }
578
579                 if (!(result = mysql_store_result(&mysql))) {
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                 while ((row = mysql_fetch_row(result))) {
589                         struct column *entry;
590                         char *cdrvar = "", *staticvalue = "";
591
592                         ast_debug(1, "Got a field '%s' of type '%s'\n", row[0], row[1]);
593                         /* Check for an alias or a static value */
594                         for (var = ast_variable_browse(cfg, "columns"); var; var = var->next) {
595                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, row[0]) == 0 ) {
596                                         char *alias = ast_strdupa(var->name + 5);
597                                         cdrvar = ast_strip(alias);
598                                         ast_verb(3, "Found alias %s for column %s\n", cdrvar, row[0]);
599                                         break;
600                                 } else if (strncmp(var->name, "static", 6) == 0 && strcasecmp(var->value, row[0]) == 0) {
601                                         char *item = ast_strdupa(var->name + 6);
602                                         item = ast_strip(item);
603                                         if (item[0] == '"' && item[strlen(item) - 1] == '"') {
604                                                 /* Remove surrounding quotes */
605                                                 item[strlen(item) - 1] = '\0';
606                                                 item++;
607                                         }
608                                         staticvalue = item;
609                                 }
610                         }
611
612                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(row[0]) + 1 + strlen(cdrvar) + 1 + strlen(staticvalue) + 1 + strlen(row[1]) + 1);
613                         if (!entry) {
614                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s'\n", row[0]);
615                                 res = -1;
616                                 break;
617                         }
618
619                         entry->name = (char *)entry + sizeof(*entry);
620                         strcpy(entry->name, row[0]);
621
622                         if (!ast_strlen_zero(cdrvar)) {
623                                 entry->cdrname = entry->name + strlen(row[0]) + 1;
624                                 strcpy(entry->cdrname, cdrvar);
625                         } else { /* Point to same place as the column name */
626                                 entry->cdrname = (char *)entry + sizeof(*entry);
627                         }
628
629                         if (!ast_strlen_zero(staticvalue)) {
630                                 entry->staticvalue = entry->cdrname + strlen(entry->cdrname) + 1;
631                                 strcpy(entry->staticvalue, staticvalue);
632                                 ast_debug(1, "staticvalue length: %d\n", (int) strlen(staticvalue) );
633                                 entry->type = entry->staticvalue + strlen(entry->staticvalue) + 1;
634                         } else {
635                                 entry->type = entry->cdrname + strlen(entry->cdrname) + 1;
636                         }
637                         strcpy(entry->type, row[1]);
638
639                         ast_debug(1, "Entry name '%s'\n", entry->name);
640                         ast_debug(1, "   cdrname '%s'\n", entry->cdrname);
641                         ast_debug(1, "    static '%s'\n", entry->staticvalue);
642                         ast_debug(1, "      type '%s'\n", entry->type);
643
644                         AST_LIST_INSERT_TAIL(&columns, entry, list);
645                 }
646                 mysql_free_result(result);
647         }
648         AST_RWLIST_UNLOCK(&columns);
649         ast_config_destroy(cfg);
650         if (res < 0) {
651                 return AST_MODULE_LOAD_FAILURE;
652         }
653
654         res = ast_cdr_register(name, desc, mysql_log);
655         if (res) {
656                 ast_log(LOG_ERROR, "Unable to register MySQL CDR handling\n");
657         } else {
658                 res = ast_cli_register_multiple(cdr_mysql_status_cli, sizeof(cdr_mysql_status_cli) / sizeof(struct ast_cli_entry));
659         }
660
661         return res;
662 }
663
664 static int load_module(void)
665 {
666         return my_load_module(0);
667 }
668
669 static int unload_module(void)
670 {
671         return my_unload_module(0);
672 }
673
674 static int reload(void)
675 {
676         int ret;
677
678         ast_mutex_lock(&mysql_lock);
679         ret = my_load_module(1);
680         ast_mutex_unlock(&mysql_lock);
681
682         return ret;
683 }
684
685 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "MySQL CDR Backend",
686         .load = load_module,
687         .unload = unload_module,
688         .reload = reload,
689 );
690