Bug 6417 - Allow retrieval of raw CDR values
[asterisk/asterisk.git] / cdr.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Call Detail Record API 
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * \note Includes code and algorithms from the Zapata library.
26  *
27  * \note We do a lot of checking here in the CDR code to try to be sure we don't ever let a CDR slip
28  * through our fingers somehow.  If someone allocates a CDR, it must be completely handled normally
29  * or a WARNING shall be logged, so that we can best keep track of any escape condition where the CDR
30  * isn't properly generated and posted.
31  */
32
33
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdio.h>
38 #include <signal.h>
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include "asterisk/lock.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/cdr.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/callerid.h"
49 #include "asterisk/causes.h"
50 #include "asterisk/options.h"
51 #include "asterisk/linkedlists.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/sched.h"
54 #include "asterisk/config.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/module.h"
57 #include "asterisk/stringfields.h"
58
59 /*! Default AMA flag for billing records (CDR's) */
60 int ast_default_amaflags = AST_CDR_DOCUMENTATION;
61 char ast_default_accountcode[AST_MAX_ACCOUNT_CODE] = "";
62
63 struct ast_cdr_beitem {
64         char name[20];
65         char desc[80];
66         ast_cdrbe be;
67         AST_LIST_ENTRY(ast_cdr_beitem) list;
68 };
69
70 static AST_LIST_HEAD_STATIC(be_list, ast_cdr_beitem);
71
72 struct ast_cdr_batch_item {
73         struct ast_cdr *cdr;
74         struct ast_cdr_batch_item *next;
75 };
76
77 static struct ast_cdr_batch {
78         int size;
79         struct ast_cdr_batch_item *head;
80         struct ast_cdr_batch_item *tail;
81 } *batch = NULL;
82
83 static struct sched_context *sched;
84 static int cdr_sched = -1;
85 static pthread_t cdr_thread = AST_PTHREADT_NULL;
86
87 #define BATCH_SIZE_DEFAULT 100
88 #define BATCH_TIME_DEFAULT 300
89 #define BATCH_SCHEDULER_ONLY_DEFAULT 0
90 #define BATCH_SAFE_SHUTDOWN_DEFAULT 1
91
92 static int enabled;
93 static int batchmode;
94 static int batchsize;
95 static int batchtime;
96 static int batchscheduleronly;
97 static int batchsafeshutdown;
98
99 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
100
101 /* these are used to wake up the CDR thread when there's work to do */
102 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
103 static ast_cond_t cdr_pending_cond;
104
105
106 /*! Register a CDR driver. Each registered CDR driver generates a CDR 
107         \return 0 on success, -1 on failure 
108 */
109 int ast_cdr_register(char *name, char *desc, ast_cdrbe be)
110 {
111         struct ast_cdr_beitem *i;
112
113         if (!name)
114                 return -1;
115         if (!be) {
116                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
117                 return -1;
118         }
119
120         AST_LIST_LOCK(&be_list);
121         AST_LIST_TRAVERSE(&be_list, i, list) {
122                 if (!strcasecmp(name, i->name))
123                         break;
124         }
125         AST_LIST_UNLOCK(&be_list);
126
127         if (i) {
128                 ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
129                 return -1;
130         }
131
132         if (!(i = ast_calloc(1, sizeof(*i))))   
133                 return -1;
134
135         i->be = be;
136         ast_copy_string(i->name, name, sizeof(i->name));
137         ast_copy_string(i->desc, desc, sizeof(i->desc));
138
139         AST_LIST_LOCK(&be_list);
140         AST_LIST_INSERT_HEAD(&be_list, i, list);
141         AST_LIST_UNLOCK(&be_list);
142
143         return 0;
144 }
145
146 /*! unregister a CDR driver */
147 void ast_cdr_unregister(char *name)
148 {
149         struct ast_cdr_beitem *i = NULL;
150
151         AST_LIST_LOCK(&be_list);
152         AST_LIST_TRAVERSE_SAFE_BEGIN(&be_list, i, list) {
153                 if (!strcasecmp(name, i->name)) {
154                         AST_LIST_REMOVE_CURRENT(&be_list, list);
155                         if (option_verbose > 1)
156                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered '%s' CDR backend\n", name);
157                         free(i);
158                         break;
159                 }
160         }
161         AST_LIST_TRAVERSE_SAFE_END;
162         AST_LIST_UNLOCK(&be_list);
163 }
164
165 /*! Duplicate a CDR record 
166         \returns Pointer to new CDR record
167 */
168 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr) 
169 {
170         struct ast_cdr *newcdr;
171
172         if (!(newcdr = ast_cdr_alloc())) {
173                 return NULL;
174         }
175
176         memcpy(newcdr, cdr, sizeof(*newcdr));
177         /* The varshead is unusable, volatile even, after the memcpy so we take care of that here */
178         memset(&newcdr->varshead, 0, sizeof(newcdr->varshead));
179         ast_cdr_copy_vars(newcdr, cdr);
180         newcdr->next = NULL;
181
182         return newcdr;
183 }
184
185 static const char *ast_cdr_getvar_internal(struct ast_cdr *cdr, const char *name, int recur) 
186 {
187         struct ast_var_t *variables;
188         struct varshead *headp;
189
190         if (ast_strlen_zero(name))
191                 return NULL;
192
193         while (cdr) {
194                 headp = &cdr->varshead;
195                 AST_LIST_TRAVERSE(headp, variables, entries) {
196                         if (!strcasecmp(name, ast_var_name(variables)))
197                                 return ast_var_value(variables);
198                 }
199                 if (!recur)
200                         break;
201                 cdr = cdr->next;
202         }
203
204         return NULL;
205 }
206
207 /*! CDR channel variable retrieval */
208 void ast_cdr_getvar(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int recur, int raw) 
209 {
210         struct tm tm;
211         time_t t;
212         const char *fmt = "%Y-%m-%d %T";
213         const char *varbuf;
214
215         *ret = NULL;
216         /* special vars (the ones from the struct ast_cdr when requested by name) 
217            I'd almost say we should convert all the stringed vals to vars */
218
219         if (!strcasecmp(name, "clid"))
220                 ast_copy_string(workspace, cdr->clid, workspacelen);
221         else if (!strcasecmp(name, "src"))
222                 ast_copy_string(workspace, cdr->src, workspacelen);
223         else if (!strcasecmp(name, "dst"))
224                 ast_copy_string(workspace, cdr->dst, workspacelen);
225         else if (!strcasecmp(name, "dcontext"))
226                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
227         else if (!strcasecmp(name, "channel"))
228                 ast_copy_string(workspace, cdr->channel, workspacelen);
229         else if (!strcasecmp(name, "dstchannel"))
230                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
231         else if (!strcasecmp(name, "lastapp"))
232                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
233         else if (!strcasecmp(name, "lastdata"))
234                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
235         else if (!strcasecmp(name, "start")) {
236                 if (raw) {
237                         snprintf(workspace, workspacelen, "%ld.%06ld", (long)cdr->start.tv_sec, (long)cdr->start.tv_usec);
238                 } else {
239                         t = cdr->start.tv_sec;
240                         if (t) {
241                                 localtime_r(&t, &tm);
242                                 strftime(workspace, workspacelen, fmt, &tm);
243                         }
244                 }
245         } else if (!strcasecmp(name, "answer")) {
246                 if (raw) {
247                         snprintf(workspace, workspacelen, "%ld.%06ld", (long)cdr->answer.tv_sec, (long)cdr->answer.tv_usec);
248                 } else {
249                         t = cdr->answer.tv_sec;
250                         if (t) {
251                                 localtime_r(&t, &tm);
252                                 strftime(workspace, workspacelen, fmt, &tm);
253                         }
254                 }
255         } else if (!strcasecmp(name, "end")) {
256                 if (raw) {
257                         snprintf(workspace, workspacelen, "%ld.%06ld", (long)cdr->end.tv_sec, (long)cdr->end.tv_usec);
258                 } else {
259                         t = cdr->end.tv_sec;
260                         if (t) {
261                                 localtime_r(&t, &tm);
262                                 strftime(workspace, workspacelen, fmt, &tm);
263                         }
264                 }
265         } else if (!strcasecmp(name, "duration"))
266                 snprintf(workspace, workspacelen, "%d", cdr->duration);
267         else if (!strcasecmp(name, "billsec"))
268                 snprintf(workspace, workspacelen, "%d", cdr->billsec);
269         else if (!strcasecmp(name, "disposition")) {
270                 if (raw) {
271                         snprintf(workspace, workspacelen, "%d", cdr->disposition);
272                 } else {
273                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
274                 }
275         } else if (!strcasecmp(name, "amaflags")) {
276                 if (raw) {
277                         snprintf(workspace, workspacelen, "%d", cdr->amaflags);
278                 } else {
279                         ast_copy_string(workspace, ast_cdr_flags2str(cdr->amaflags), workspacelen);
280                 }
281         } else if (!strcasecmp(name, "accountcode"))
282                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
283         else if (!strcasecmp(name, "uniqueid"))
284                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
285         else if (!strcasecmp(name, "userfield"))
286                 ast_copy_string(workspace, cdr->userfield, workspacelen);
287         else if ((varbuf = ast_cdr_getvar_internal(cdr, name, recur)))
288                 ast_copy_string(workspace, varbuf, workspacelen);
289
290         if (!ast_strlen_zero(workspace))
291                 *ret = workspace;
292 }
293
294 /* readonly cdr variables */
295 static  const char *cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
296                                     "lastapp", "lastdata", "start", "answer", "end", "duration",
297                                     "billsec", "disposition", "amaflags", "accountcode", "uniqueid",
298                                     "userfield", NULL };
299 /*! Set a CDR channel variable 
300         \note You can't set the CDR variables that belong to the actual CDR record, like "billsec".
301 */
302 int ast_cdr_setvar(struct ast_cdr *cdr, const char *name, const char *value, int recur) 
303 {
304         struct ast_var_t *newvariable;
305         struct varshead *headp;
306         int x;
307         
308         for(x = 0; cdr_readonly_vars[x]; x++) {
309                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
310                         ast_log(LOG_ERROR, "Attempt to set a read-only variable!.\n");
311                         return -1;
312                 }
313         }
314
315         if (!cdr) {
316                 ast_log(LOG_ERROR, "Attempt to set a variable on a nonexistent CDR record.\n");
317                 return -1;
318         }
319
320         while (cdr) {
321                 headp = &cdr->varshead;
322                 AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
323                         if (!strcasecmp(ast_var_name(newvariable), name)) {
324                                 /* there is already such a variable, delete it */
325                                 AST_LIST_REMOVE_CURRENT(headp, entries);
326                                 ast_var_delete(newvariable);
327                                 break;
328                         }
329                 }
330                 AST_LIST_TRAVERSE_SAFE_END;
331
332                 if (value) {
333                         newvariable = ast_var_assign(name, value);
334                         AST_LIST_INSERT_HEAD(headp, newvariable, entries);
335                 }
336
337                 if (!recur) {
338                         break;
339                 }
340
341                 cdr = cdr->next;
342         }
343
344         return 0;
345 }
346
347 int ast_cdr_copy_vars(struct ast_cdr *to_cdr, struct ast_cdr *from_cdr)
348 {
349         struct ast_var_t *variables, *newvariable = NULL;
350         struct varshead *headpa, *headpb;
351         const char *var, *val;
352         int x = 0;
353
354         headpa = &from_cdr->varshead;
355         headpb = &to_cdr->varshead;
356
357         AST_LIST_TRAVERSE(headpa,variables,entries) {
358                 if (variables &&
359                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
360                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
361                         newvariable = ast_var_assign(var, val);
362                         AST_LIST_INSERT_HEAD(headpb, newvariable, entries);
363                         x++;
364                 }
365         }
366
367         return x;
368 }
369
370 int ast_cdr_serialize_variables(struct ast_cdr *cdr, char *buf, size_t size, char delim, char sep, int recur) 
371 {
372         struct ast_var_t *variables;
373         const char *var, *val;
374         char *tmp;
375         char workspace[256];
376         int total = 0, x = 0, i;
377
378         memset(buf, 0, size);
379
380         for (; cdr; cdr = recur ? cdr->next : NULL) {
381                 if (++x > 1)
382                         ast_build_string(&buf, &size, "\n");
383
384                 AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
385                         if (variables &&
386                             (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
387                             !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
388                                 if (ast_build_string(&buf, &size, "level %d: %s%c%s%c", x, var, delim, val, sep)) {
389                                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
390                                         break;
391                                 } else
392                                         total++;
393                         } else 
394                                 break;
395                 }
396
397                 for (i = 0; cdr_readonly_vars[i]; i++) {
398                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
399                         if (!tmp)
400                                 continue;
401                         
402                         if (ast_build_string(&buf, &size, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep)) {
403                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
404                                 break;
405                         } else
406                                 total++;
407                 }
408         }
409
410         return total;
411 }
412
413
414 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
415 {
416         struct varshead *headp;
417         struct ast_var_t *vardata;
418
419         /* clear variables */
420         while (cdr) {
421                 headp = &cdr->varshead;
422                 while (!AST_LIST_EMPTY(headp)) {
423                         vardata = AST_LIST_REMOVE_HEAD(headp, entries);
424                         ast_var_delete(vardata);
425                 }
426
427                 if (!recur) {
428                         break;
429                 }
430
431                 cdr = cdr->next;
432         }
433 }
434
435 void ast_cdr_free(struct ast_cdr *cdr)
436 {
437         char *chan;
438         struct ast_cdr *next; 
439
440         while (cdr) {
441                 next = cdr->next;
442                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
443                 if (!ast_test_flag(cdr, AST_CDR_FLAG_POSTED) && !ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
444                         ast_log(LOG_WARNING, "CDR on channel '%s' not posted\n", chan);
445                 if (ast_tvzero(cdr->end))
446                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
447                 if (ast_tvzero(cdr->start))
448                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
449
450                 ast_cdr_free_vars(cdr, 0);
451                 free(cdr);
452                 cdr = next;
453         }
454 }
455
456 struct ast_cdr *ast_cdr_alloc(void)
457 {
458         return ast_calloc(1, sizeof(struct ast_cdr));
459 }
460
461 void ast_cdr_start(struct ast_cdr *cdr)
462 {
463         char *chan; 
464
465         while (cdr) {
466                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
467                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
468                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
469                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
470                         if (!ast_tvzero(cdr->start))
471                                 ast_log(LOG_WARNING, "CDR on channel '%s' already started\n", chan);
472                         cdr->start = ast_tvnow();
473                 }
474                 cdr = cdr->next;
475         }
476 }
477
478 void ast_cdr_answer(struct ast_cdr *cdr)
479 {
480         char *chan; 
481
482         while (cdr) {
483                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
484                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
485                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
486                 if (cdr->disposition < AST_CDR_ANSWERED)
487                         cdr->disposition = AST_CDR_ANSWERED;
488                 if (ast_tvzero(cdr->answer))
489                         cdr->answer = ast_tvnow();
490                 cdr = cdr->next;
491         }
492 }
493
494 void ast_cdr_busy(struct ast_cdr *cdr)
495 {
496         char *chan; 
497
498         while (cdr) {
499                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
500                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
501                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
502                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
503                         if (cdr->disposition < AST_CDR_BUSY)
504                                 cdr->disposition = AST_CDR_BUSY;
505                 }
506                 cdr = cdr->next;
507         }
508 }
509
510 void ast_cdr_failed(struct ast_cdr *cdr)
511 {
512         char *chan; 
513
514         while (cdr) {
515                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
516                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
517                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
518                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
519                         cdr->disposition = AST_CDR_FAILED;
520                 cdr = cdr->next;
521         }
522 }
523
524 int ast_cdr_disposition(struct ast_cdr *cdr, int cause)
525 {
526         int res = 0;
527
528         while (cdr) {
529                 switch(cause) {
530                 case AST_CAUSE_BUSY:
531                         ast_cdr_busy(cdr);
532                         break;
533                 case AST_CAUSE_FAILURE:
534                         ast_cdr_failed(cdr);
535                         break;
536                 case AST_CAUSE_NORMAL:
537                         break;
538                 case AST_CAUSE_NOTDEFINED:
539                         res = -1;
540                         break;
541                 default:
542                         res = -1;
543                         ast_log(LOG_WARNING, "Cause not handled\n");
544                 }
545                 cdr = cdr->next;
546         }
547         return res;
548 }
549
550 void ast_cdr_setdestchan(struct ast_cdr *cdr, const char *chann)
551 {
552         char *chan; 
553
554         while (cdr) {
555                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
556                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
557                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
558                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
559                         ast_copy_string(cdr->dstchannel, chann, sizeof(cdr->dstchannel));
560                 cdr = cdr->next;
561         }
562 }
563
564 void ast_cdr_setapp(struct ast_cdr *cdr, char *app, char *data)
565 {
566         char *chan; 
567
568         while (cdr) {
569                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
570                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
571                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
572                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
573                         if (!app)
574                                 app = "";
575                         ast_copy_string(cdr->lastapp, app, sizeof(cdr->lastapp));
576                         if (!data)
577                                 data = "";
578                         ast_copy_string(cdr->lastdata, data, sizeof(cdr->lastdata));
579                 }
580                 cdr = cdr->next;
581         }
582 }
583
584 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
585 {
586         char tmp[AST_MAX_EXTENSION] = "";
587         char *num;
588
589         while (cdr) {
590                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
591                         /* Grab source from ANI or normal Caller*ID */
592                         num = c->cid.cid_ani ? c->cid.cid_ani : c->cid.cid_num;
593                         
594                         if (c->cid.cid_name && num)
595                                 snprintf(tmp, sizeof(tmp), "\"%s\" <%s>", c->cid.cid_name, num);
596                         else if (c->cid.cid_name)
597                                 ast_copy_string(tmp, c->cid.cid_name, sizeof(tmp));
598                         else if (num)
599                                 ast_copy_string(tmp, num, sizeof(tmp));
600                         ast_copy_string(cdr->clid, tmp, sizeof(cdr->clid));
601                         ast_copy_string(cdr->src, num ? num : "", sizeof(cdr->src));
602                 }
603                 cdr = cdr->next;
604         }
605
606         return 0;
607 }
608
609
610 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
611 {
612         char *chan;
613         char *num;
614         char tmp[AST_MAX_EXTENSION] = "";
615
616         while (cdr) {
617                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
618                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
619                         if (!ast_strlen_zero(cdr->channel)) 
620                                 ast_log(LOG_WARNING, "CDR already initialized on '%s'\n", chan); 
621                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
622                         /* Grab source from ANI or normal Caller*ID */
623                         num = c->cid.cid_ani ? c->cid.cid_ani : c->cid.cid_num;
624                         
625                         if (c->cid.cid_name && num)
626                                 snprintf(tmp, sizeof(tmp), "\"%s\" <%s>", c->cid.cid_name, num);
627                         else if (c->cid.cid_name)
628                                 ast_copy_string(tmp, c->cid.cid_name, sizeof(tmp));
629                         else if (num)
630                                 ast_copy_string(tmp, num, sizeof(tmp));
631                         ast_copy_string(cdr->clid, tmp, sizeof(cdr->clid));
632                         ast_copy_string(cdr->src, num ? num : "", sizeof(cdr->src));
633
634                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NOANSWER;
635                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
636                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
637                         /* Destination information */
638                         ast_copy_string(cdr->dst, c->exten, sizeof(cdr->dst));
639                         ast_copy_string(cdr->dcontext, c->context, sizeof(cdr->dcontext));
640                         /* Unique call identifier */
641                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
642                 }
643                 cdr = cdr->next;
644         }
645         return 0;
646 }
647
648 void ast_cdr_end(struct ast_cdr *cdr)
649 {
650         char *chan;
651
652         while (cdr) {
653                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
654                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
655                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
656                 if (ast_tvzero(cdr->start))
657                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", chan);
658                 if (ast_tvzero(cdr->end))
659                         cdr->end = ast_tvnow();
660                 cdr = cdr->next;
661         }
662 }
663
664 char *ast_cdr_disp2str(int disposition)
665 {
666         switch (disposition) {
667         case AST_CDR_NOANSWER:
668                 return "NO ANSWER";
669         case AST_CDR_FAILED:
670                 return "FAILED";                
671         case AST_CDR_BUSY:
672                 return "BUSY";          
673         case AST_CDR_ANSWERED:
674                 return "ANSWERED";
675         }
676         return "UNKNOWN";
677 }
678
679 /*! Converts AMA flag to printable string */
680 char *ast_cdr_flags2str(int flag)
681 {
682         switch(flag) {
683         case AST_CDR_OMIT:
684                 return "OMIT";
685         case AST_CDR_BILLING:
686                 return "BILLING";
687         case AST_CDR_DOCUMENTATION:
688                 return "DOCUMENTATION";
689         }
690         return "Unknown";
691 }
692
693 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
694 {
695         struct ast_cdr *cdr = chan->cdr;
696
697         ast_string_field_set(chan, accountcode, account);
698         while (cdr) {
699                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
700                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
701                 cdr = cdr->next;
702         }
703         return 0;
704 }
705
706 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
707 {
708         struct ast_cdr *cdr;
709         int newflag;
710
711         newflag = ast_cdr_amaflags2int(flag);
712         if (newflag) {
713                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
714                         cdr->amaflags = newflag;
715                 }
716         }
717
718         return 0;
719 }
720
721 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
722 {
723         struct ast_cdr *cdr = chan->cdr;
724
725         while (cdr) {
726                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
727                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
728                 cdr = cdr->next;
729         }
730
731         return 0;
732 }
733
734 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
735 {
736         struct ast_cdr *cdr = chan->cdr;
737
738         while (cdr) {
739                 int len = strlen(cdr->userfield);
740
741                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
742                         strncpy(cdr->userfield+len, userfield, sizeof(cdr->userfield) - len - 1);
743
744                 cdr = cdr->next;
745         }
746
747         return 0;
748 }
749
750 int ast_cdr_update(struct ast_channel *c)
751 {
752         struct ast_cdr *cdr = c->cdr;
753         char *num;
754         char tmp[AST_MAX_EXTENSION] = "";
755
756         while (cdr) {
757                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
758                         num = c->cid.cid_ani ? c->cid.cid_ani : c->cid.cid_num;
759                         
760                         if (c->cid.cid_name && num)
761                                 snprintf(tmp, sizeof(tmp), "\"%s\" <%s>", c->cid.cid_name, num);
762                         else if (c->cid.cid_name)
763                                 ast_copy_string(tmp, c->cid.cid_name, sizeof(tmp));
764                         else if (num)
765                                 ast_copy_string(tmp, num, sizeof(tmp));
766                         ast_copy_string(cdr->clid, tmp, sizeof(cdr->clid));
767                         ast_copy_string(cdr->src, num ? num : "", sizeof(cdr->src));
768
769                         /* Copy account code et-al */   
770                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
771                         /* Destination information */
772                         ast_copy_string(cdr->dst, (ast_strlen_zero(c->macroexten)) ? c->exten : c->macroexten, sizeof(cdr->dst));
773                         ast_copy_string(cdr->dcontext, (ast_strlen_zero(c->macrocontext)) ? c->context : c->macrocontext, sizeof(cdr->dcontext));
774                 }
775                 cdr = cdr->next;
776         }
777
778         return 0;
779 }
780
781 int ast_cdr_amaflags2int(const char *flag)
782 {
783         if (!strcasecmp(flag, "default"))
784                 return 0;
785         if (!strcasecmp(flag, "omit"))
786                 return AST_CDR_OMIT;
787         if (!strcasecmp(flag, "billing"))
788                 return AST_CDR_BILLING;
789         if (!strcasecmp(flag, "documentation"))
790                 return AST_CDR_DOCUMENTATION;
791         return -1;
792 }
793
794 static void post_cdr(struct ast_cdr *cdr)
795 {
796         char *chan;
797         struct ast_cdr_beitem *i;
798
799         while (cdr) {
800                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
801                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
802                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
803                 if (ast_tvzero(cdr->end))
804                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
805                 if (ast_tvzero(cdr->start))
806                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
807                 cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec + (cdr->end.tv_usec - cdr->start.tv_usec) / 1000000;
808                 if (!ast_tvzero(cdr->answer))
809                         cdr->billsec = cdr->end.tv_sec - cdr->answer.tv_sec + (cdr->end.tv_usec - cdr->answer.tv_usec) / 1000000;
810                 else
811                         cdr->billsec = 0;
812                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
813                 AST_LIST_LOCK(&be_list);
814                 AST_LIST_TRAVERSE(&be_list, i, list) {
815                         i->be(cdr);
816                 }
817                 AST_LIST_UNLOCK(&be_list);
818                 cdr = cdr->next;
819         }
820 }
821
822 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
823 {
824         struct ast_cdr *dup;
825         struct ast_flags flags = { 0 };
826
827         if (_flags)
828                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
829
830         while (cdr) {
831                 /* Detach if post is requested */
832                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
833                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
834                                 ast_cdr_end(cdr);
835                                 if ((dup = ast_cdr_dup(cdr))) {
836                                         ast_cdr_detach(dup);
837                                 }
838                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
839                         }
840
841                         /* clear variables */
842                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
843                                 ast_cdr_free_vars(cdr, 0);
844                         }
845
846                         /* Reset to initial state */
847                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
848                         memset(&cdr->start, 0, sizeof(cdr->start));
849                         memset(&cdr->end, 0, sizeof(cdr->end));
850                         memset(&cdr->answer, 0, sizeof(cdr->answer));
851                         cdr->billsec = 0;
852                         cdr->duration = 0;
853                         ast_cdr_start(cdr);
854                         cdr->disposition = AST_CDR_NOANSWER;
855                 }
856                         
857                 cdr = cdr->next;
858         }
859 }
860
861 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
862 {
863         struct ast_cdr *ret;
864
865         if (cdr) {
866                 ret = cdr;
867
868                 while (cdr->next)
869                         cdr = cdr->next;
870                 cdr->next = newcdr;
871         } else {
872                 ret = newcdr;
873         }
874
875         return ret;
876 }
877
878 /*! \note Don't call without cdr_batch_lock */
879 static void reset_batch(void)
880 {
881         batch->size = 0;
882         batch->head = NULL;
883         batch->tail = NULL;
884 }
885
886 /*! \note Don't call without cdr_batch_lock */
887 static int init_batch(void)
888 {
889         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
890         if (!(batch = ast_malloc(sizeof(*batch)))) {
891                 return -1;
892         }
893
894         reset_batch();
895
896         return 0;
897 }
898
899 static void *do_batch_backend_process(void *data)
900 {
901         struct ast_cdr_batch_item *processeditem;
902         struct ast_cdr_batch_item *batchitem = data;
903
904         /* Push each CDR into storage mechanism(s) and free all the memory */
905         while (batchitem) {
906                 post_cdr(batchitem->cdr);
907                 ast_cdr_free(batchitem->cdr);
908                 processeditem = batchitem;
909                 batchitem = batchitem->next;
910                 free(processeditem);
911         }
912
913         return NULL;
914 }
915
916 void ast_cdr_submit_batch(int shutdown)
917 {
918         struct ast_cdr_batch_item *oldbatchitems = NULL;
919         pthread_attr_t attr;
920         pthread_t batch_post_thread = AST_PTHREADT_NULL;
921
922         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
923         if (!batch || !batch->head)
924                 return;
925
926         /* move the old CDRs aside, and prepare a new CDR batch */
927         ast_mutex_lock(&cdr_batch_lock);
928         oldbatchitems = batch->head;
929         reset_batch();
930         ast_mutex_unlock(&cdr_batch_lock);
931
932         /* if configured, spawn a new thread to post these CDRs,
933            also try to save as much as possible if we are shutting down safely */
934         if (batchscheduleronly || shutdown) {
935                 if (option_debug)
936                         ast_log(LOG_DEBUG, "CDR single-threaded batch processing begins now\n");
937                 do_batch_backend_process(oldbatchitems);
938         } else {
939                 pthread_attr_init(&attr);
940                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
941                 if (ast_pthread_create(&batch_post_thread, &attr, do_batch_backend_process, oldbatchitems)) {
942                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
943                         do_batch_backend_process(oldbatchitems);
944                 } else {
945                         if (option_debug)
946                                 ast_log(LOG_DEBUG, "CDR multi-threaded batch processing begins now\n");
947                 }
948         }
949 }
950
951 static int submit_scheduled_batch(void *data)
952 {
953         ast_cdr_submit_batch(0);
954         /* manually reschedule from this point in time */
955         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
956         /* returning zero so the scheduler does not automatically reschedule */
957         return 0;
958 }
959
960 static void submit_unscheduled_batch(void)
961 {
962         /* this is okay since we are not being called from within the scheduler */
963         if (cdr_sched > -1)
964                 ast_sched_del(sched, cdr_sched);
965         /* schedule the submission to occur ASAP (1 ms) */
966         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
967         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
968         ast_mutex_lock(&cdr_pending_lock);
969         ast_cond_signal(&cdr_pending_cond);
970         ast_mutex_unlock(&cdr_pending_lock);
971 }
972
973 void ast_cdr_detach(struct ast_cdr *cdr)
974 {
975         struct ast_cdr_batch_item *newtail;
976         int curr;
977
978         /* maybe they disabled CDR stuff completely, so just drop it */
979         if (!enabled) {
980                 if (option_debug)
981                         ast_log(LOG_DEBUG, "Dropping CDR !\n");
982                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
983                 ast_cdr_free(cdr);
984                 return;
985         }
986
987         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
988         if (!batchmode) {
989                 post_cdr(cdr);
990                 ast_cdr_free(cdr);
991                 return;
992         }
993
994         /* otherwise, each CDR gets put into a batch list (at the end) */
995         if (option_debug)
996                 ast_log(LOG_DEBUG, "CDR detaching from this thread\n");
997
998         /* we'll need a new tail for every CDR */       
999         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
1000                 post_cdr(cdr);
1001                 ast_cdr_free(cdr);
1002                 return;
1003         }
1004
1005         /* don't traverse a whole list (just keep track of the tail) */
1006         ast_mutex_lock(&cdr_batch_lock);
1007         if (!batch)
1008                 init_batch();
1009         if (!batch->head) {
1010                 /* new batch is empty, so point the head at the new tail */
1011                 batch->head = newtail;
1012         } else {
1013                 /* already got a batch with something in it, so just append a new tail */
1014                 batch->tail->next = newtail;
1015         }
1016         newtail->cdr = cdr;
1017         batch->tail = newtail;
1018         curr = batch->size++;
1019         ast_mutex_unlock(&cdr_batch_lock);
1020
1021         /* if we have enough stuff to post, then do it */
1022         if (curr >= (batchsize - 1))
1023                 submit_unscheduled_batch();
1024 }
1025
1026 static void *do_cdr(void *data)
1027 {
1028         struct timespec timeout;
1029         int schedms;
1030         int numevents = 0;
1031
1032         for(;;) {
1033                 struct timeval now = ast_tvnow();
1034                 schedms = ast_sched_wait(sched);
1035                 /* this shouldn't happen, but provide a 1 second default just in case */
1036                 if (schedms <= 0)
1037                         schedms = 1000;
1038                 timeout.tv_sec = now.tv_sec + (schedms / 1000);
1039                 timeout.tv_nsec = (now.tv_usec * 1000) + ((schedms % 1000) * 1000);
1040                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
1041                 ast_mutex_lock(&cdr_pending_lock);
1042                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
1043                 numevents = ast_sched_runq(sched);
1044                 ast_mutex_unlock(&cdr_pending_lock);
1045                 if (option_debug > 1)
1046                         ast_log(LOG_DEBUG, "Processed %d scheduled CDR batches from the run queue\n", numevents);
1047         }
1048
1049         return NULL;
1050 }
1051
1052 static int handle_cli_status(int fd, int argc, char *argv[])
1053 {
1054         struct ast_cdr_beitem *beitem=NULL;
1055         int cnt=0;
1056         long nextbatchtime=0;
1057
1058         if (argc > 2)
1059                 return RESULT_SHOWUSAGE;
1060
1061         ast_cli(fd, "CDR logging: %s\n", enabled ? "enabled" : "disabled");
1062         ast_cli(fd, "CDR mode: %s\n", batchmode ? "batch" : "simple");
1063         if (enabled) {
1064                 if (batchmode) {
1065                         if (batch)
1066                                 cnt = batch->size;
1067                         if (cdr_sched > -1)
1068                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
1069                         ast_cli(fd, "CDR safe shut down: %s\n", batchsafeshutdown ? "enabled" : "disabled");
1070                         ast_cli(fd, "CDR batch threading model: %s\n", batchscheduleronly ? "scheduler only" : "scheduler plus separate threads");
1071                         ast_cli(fd, "CDR current batch size: %d record%s\n", cnt, (cnt != 1) ? "s" : "");
1072                         ast_cli(fd, "CDR maximum batch size: %d record%s\n", batchsize, (batchsize != 1) ? "s" : "");
1073                         ast_cli(fd, "CDR maximum batch time: %d second%s\n", batchtime, (batchtime != 1) ? "s" : "");
1074                         ast_cli(fd, "CDR next scheduled batch processing time: %ld second%s\n", nextbatchtime, (nextbatchtime != 1) ? "s" : "");
1075                 }
1076                 AST_LIST_LOCK(&be_list);
1077                 AST_LIST_TRAVERSE(&be_list, beitem, list) {
1078                         ast_cli(fd, "CDR registered backend: %s\n", beitem->name);
1079                 }
1080                 AST_LIST_UNLOCK(&be_list);
1081         }
1082
1083         return 0;
1084 }
1085
1086 static int handle_cli_submit(int fd, int argc, char *argv[])
1087 {
1088         if (argc > 2)
1089                 return RESULT_SHOWUSAGE;
1090
1091         submit_unscheduled_batch();
1092         ast_cli(fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1093
1094         return 0;
1095 }
1096
1097 static struct ast_cli_entry cli_submit = {
1098         .cmda = { "cdr", "submit", NULL },
1099         .handler = handle_cli_submit,
1100         .summary = "Posts all pending batched CDR data",
1101         .usage =
1102         "Usage: cdr submit\n"
1103         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n"
1104 };
1105
1106 static struct ast_cli_entry cli_status = {
1107         .cmda = { "cdr", "status", NULL },
1108         .handler = handle_cli_status,
1109         .summary = "Display the CDR status",
1110         .usage =
1111         "Usage: cdr status\n"
1112         "       Displays the Call Detail Record engine system status.\n"
1113 };
1114
1115 static int do_reload(void)
1116 {
1117         struct ast_config *config;
1118         const char *enabled_value;
1119         const char *batched_value;
1120         const char *scheduleronly_value;
1121         const char *batchsafeshutdown_value;
1122         const char *size_value;
1123         const char *time_value;
1124         int cfg_size;
1125         int cfg_time;
1126         int was_enabled;
1127         int was_batchmode;
1128         int res=0;
1129
1130         ast_mutex_lock(&cdr_batch_lock);
1131
1132         batchsize = BATCH_SIZE_DEFAULT;
1133         batchtime = BATCH_TIME_DEFAULT;
1134         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1135         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1136         was_enabled = enabled;
1137         was_batchmode = batchmode;
1138         enabled = 1;
1139         batchmode = 0;
1140
1141         /* don't run the next scheduled CDR posting while reloading */
1142         if (cdr_sched > -1)
1143                 ast_sched_del(sched, cdr_sched);
1144
1145         if ((config = ast_config_load("cdr.conf"))) {
1146                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1147                         enabled = ast_true(enabled_value);
1148                 }
1149                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1150                         batchmode = ast_true(batched_value);
1151                 }
1152                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1153                         batchscheduleronly = ast_true(scheduleronly_value);
1154                 }
1155                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1156                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1157                 }
1158                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1159                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1160                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1161                         else if (size_value < 0)
1162                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1163                         else
1164                                 batchsize = cfg_size;
1165                 }
1166                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1167                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1168                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1169                         else if (time_value < 0)
1170                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1171                         else
1172                                 batchtime = cfg_time;
1173                 }
1174         }
1175
1176         if (enabled && !batchmode) {
1177                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1178         } else if (enabled && batchmode) {
1179                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1180                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1181         } else {
1182                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1183         }
1184
1185         /* if this reload enabled the CDR batch mode, create the background thread
1186            if it does not exist */
1187         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1188                 ast_cond_init(&cdr_pending_cond, NULL);
1189                 if (ast_pthread_create(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1190                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1191                         ast_sched_del(sched, cdr_sched);
1192                 } else {
1193                         ast_cli_register(&cli_submit);
1194                         ast_register_atexit(ast_cdr_engine_term);
1195                         res = 0;
1196                 }
1197         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1198            kill it */
1199         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1200                 /* wake up the thread so it will exit */
1201                 pthread_cancel(cdr_thread);
1202                 pthread_kill(cdr_thread, SIGURG);
1203                 pthread_join(cdr_thread, NULL);
1204                 cdr_thread = AST_PTHREADT_NULL;
1205                 ast_cond_destroy(&cdr_pending_cond);
1206                 ast_cli_unregister(&cli_submit);
1207                 ast_unregister_atexit(ast_cdr_engine_term);
1208                 res = 0;
1209                 /* if leaving batch mode, then post the CDRs in the batch,
1210                    and don't reschedule, since we are stopping CDR logging */
1211                 if (!batchmode && was_batchmode) {
1212                         ast_cdr_engine_term();
1213                 }
1214         } else {
1215                 res = 0;
1216         }
1217
1218         ast_mutex_unlock(&cdr_batch_lock);
1219         ast_config_destroy(config);
1220
1221         return res;
1222 }
1223
1224 int ast_cdr_engine_init(void)
1225 {
1226         int res;
1227
1228         sched = sched_context_create();
1229         if (!sched) {
1230                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1231                 return -1;
1232         }
1233
1234         ast_cli_register(&cli_status);
1235
1236         res = do_reload();
1237         if (res) {
1238                 ast_mutex_lock(&cdr_batch_lock);
1239                 res = init_batch();
1240                 ast_mutex_unlock(&cdr_batch_lock);
1241         }
1242
1243         return res;
1244 }
1245
1246 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1247    hanging up channels, and then again, after the channel hangup timeout expires */
1248 void ast_cdr_engine_term(void)
1249 {
1250         ast_cdr_submit_batch(batchsafeshutdown);
1251 }
1252
1253 int ast_cdr_engine_reload(void)
1254 {
1255         return do_reload();
1256 }
1257