don't calculate a duration if the CDR wasn't started, as it will result in a
[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, "%ld", cdr->duration);
267         else if (!strcasecmp(name, "billsec"))
268                 snprintf(workspace, workspacelen, "%ld", cdr->billsec);
269         else if (!strcasecmp(name, "disposition")) {
270                 if (raw) {
271                         snprintf(workspace, workspacelen, "%ld", 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, "%ld", 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->end))
657                         cdr->end = ast_tvnow();
658                 if (ast_tvzero(cdr->start))
659                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", chan);
660                 else
661                         cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
662                 if (!ast_tvzero(cdr->answer))
663                         cdr->billsec = cdr->end.tv_sec - cdr->answer.tv_sec;
664                 else
665                         cdr->billsec = 0;
666                 cdr = cdr->next;
667         }
668 }
669
670 char *ast_cdr_disp2str(int disposition)
671 {
672         switch (disposition) {
673         case AST_CDR_NOANSWER:
674                 return "NO ANSWER";
675         case AST_CDR_FAILED:
676                 return "FAILED";                
677         case AST_CDR_BUSY:
678                 return "BUSY";          
679         case AST_CDR_ANSWERED:
680                 return "ANSWERED";
681         }
682         return "UNKNOWN";
683 }
684
685 /*! Converts AMA flag to printable string */
686 char *ast_cdr_flags2str(int flag)
687 {
688         switch(flag) {
689         case AST_CDR_OMIT:
690                 return "OMIT";
691         case AST_CDR_BILLING:
692                 return "BILLING";
693         case AST_CDR_DOCUMENTATION:
694                 return "DOCUMENTATION";
695         }
696         return "Unknown";
697 }
698
699 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
700 {
701         struct ast_cdr *cdr = chan->cdr;
702
703         ast_string_field_set(chan, accountcode, account);
704         while (cdr) {
705                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
706                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
707                 cdr = cdr->next;
708         }
709         return 0;
710 }
711
712 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
713 {
714         struct ast_cdr *cdr;
715         int newflag;
716
717         newflag = ast_cdr_amaflags2int(flag);
718         if (newflag) {
719                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
720                         cdr->amaflags = newflag;
721                 }
722         }
723
724         return 0;
725 }
726
727 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
728 {
729         struct ast_cdr *cdr = chan->cdr;
730
731         while (cdr) {
732                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
733                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
734                 cdr = cdr->next;
735         }
736
737         return 0;
738 }
739
740 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
741 {
742         struct ast_cdr *cdr = chan->cdr;
743
744         while (cdr) {
745                 int len = strlen(cdr->userfield);
746
747                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
748                         strncpy(cdr->userfield+len, userfield, sizeof(cdr->userfield) - len - 1);
749
750                 cdr = cdr->next;
751         }
752
753         return 0;
754 }
755
756 int ast_cdr_update(struct ast_channel *c)
757 {
758         struct ast_cdr *cdr = c->cdr;
759         char *num;
760         char tmp[AST_MAX_EXTENSION] = "";
761
762         while (cdr) {
763                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
764                         num = c->cid.cid_ani ? c->cid.cid_ani : c->cid.cid_num;
765                         
766                         if (c->cid.cid_name && num)
767                                 snprintf(tmp, sizeof(tmp), "\"%s\" <%s>", c->cid.cid_name, num);
768                         else if (c->cid.cid_name)
769                                 ast_copy_string(tmp, c->cid.cid_name, sizeof(tmp));
770                         else if (num)
771                                 ast_copy_string(tmp, num, sizeof(tmp));
772                         ast_copy_string(cdr->clid, tmp, sizeof(cdr->clid));
773                         ast_copy_string(cdr->src, num ? num : "", sizeof(cdr->src));
774
775                         /* Copy account code et-al */   
776                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
777                         /* Destination information */
778                         ast_copy_string(cdr->dst, (ast_strlen_zero(c->macroexten)) ? c->exten : c->macroexten, sizeof(cdr->dst));
779                         ast_copy_string(cdr->dcontext, (ast_strlen_zero(c->macrocontext)) ? c->context : c->macrocontext, sizeof(cdr->dcontext));
780                 }
781                 cdr = cdr->next;
782         }
783
784         return 0;
785 }
786
787 int ast_cdr_amaflags2int(const char *flag)
788 {
789         if (!strcasecmp(flag, "default"))
790                 return 0;
791         if (!strcasecmp(flag, "omit"))
792                 return AST_CDR_OMIT;
793         if (!strcasecmp(flag, "billing"))
794                 return AST_CDR_BILLING;
795         if (!strcasecmp(flag, "documentation"))
796                 return AST_CDR_DOCUMENTATION;
797         return -1;
798 }
799
800 static void post_cdr(struct ast_cdr *cdr)
801 {
802         char *chan;
803         struct ast_cdr_beitem *i;
804
805         while (cdr) {
806                 chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
807                 if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
808                         ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
809                 if (ast_tvzero(cdr->end))
810                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
811                 if (ast_tvzero(cdr->start))
812                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
813                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
814                 AST_LIST_LOCK(&be_list);
815                 AST_LIST_TRAVERSE(&be_list, i, list) {
816                         i->be(cdr);
817                 }
818                 AST_LIST_UNLOCK(&be_list);
819                 cdr = cdr->next;
820         }
821 }
822
823 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
824 {
825         struct ast_cdr *dup;
826         struct ast_flags flags = { 0 };
827
828         if (_flags)
829                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
830
831         while (cdr) {
832                 /* Detach if post is requested */
833                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
834                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
835                                 ast_cdr_end(cdr);
836                                 if ((dup = ast_cdr_dup(cdr))) {
837                                         ast_cdr_detach(dup);
838                                 }
839                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
840                         }
841
842                         /* clear variables */
843                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
844                                 ast_cdr_free_vars(cdr, 0);
845                         }
846
847                         /* Reset to initial state */
848                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
849                         memset(&cdr->start, 0, sizeof(cdr->start));
850                         memset(&cdr->end, 0, sizeof(cdr->end));
851                         memset(&cdr->answer, 0, sizeof(cdr->answer));
852                         cdr->billsec = 0;
853                         cdr->duration = 0;
854                         ast_cdr_start(cdr);
855                         cdr->disposition = AST_CDR_NOANSWER;
856                 }
857                         
858                 cdr = cdr->next;
859         }
860 }
861
862 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
863 {
864         struct ast_cdr *ret;
865
866         if (cdr) {
867                 ret = cdr;
868
869                 while (cdr->next)
870                         cdr = cdr->next;
871                 cdr->next = newcdr;
872         } else {
873                 ret = newcdr;
874         }
875
876         return ret;
877 }
878
879 /*! \note Don't call without cdr_batch_lock */
880 static void reset_batch(void)
881 {
882         batch->size = 0;
883         batch->head = NULL;
884         batch->tail = NULL;
885 }
886
887 /*! \note Don't call without cdr_batch_lock */
888 static int init_batch(void)
889 {
890         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
891         if (!(batch = ast_malloc(sizeof(*batch)))) {
892                 return -1;
893         }
894
895         reset_batch();
896
897         return 0;
898 }
899
900 static void *do_batch_backend_process(void *data)
901 {
902         struct ast_cdr_batch_item *processeditem;
903         struct ast_cdr_batch_item *batchitem = data;
904
905         /* Push each CDR into storage mechanism(s) and free all the memory */
906         while (batchitem) {
907                 post_cdr(batchitem->cdr);
908                 ast_cdr_free(batchitem->cdr);
909                 processeditem = batchitem;
910                 batchitem = batchitem->next;
911                 free(processeditem);
912         }
913
914         return NULL;
915 }
916
917 void ast_cdr_submit_batch(int shutdown)
918 {
919         struct ast_cdr_batch_item *oldbatchitems = NULL;
920         pthread_attr_t attr;
921         pthread_t batch_post_thread = AST_PTHREADT_NULL;
922
923         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
924         if (!batch || !batch->head)
925                 return;
926
927         /* move the old CDRs aside, and prepare a new CDR batch */
928         ast_mutex_lock(&cdr_batch_lock);
929         oldbatchitems = batch->head;
930         reset_batch();
931         ast_mutex_unlock(&cdr_batch_lock);
932
933         /* if configured, spawn a new thread to post these CDRs,
934            also try to save as much as possible if we are shutting down safely */
935         if (batchscheduleronly || shutdown) {
936                 if (option_debug)
937                         ast_log(LOG_DEBUG, "CDR single-threaded batch processing begins now\n");
938                 do_batch_backend_process(oldbatchitems);
939         } else {
940                 pthread_attr_init(&attr);
941                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
942                 if (ast_pthread_create(&batch_post_thread, &attr, do_batch_backend_process, oldbatchitems)) {
943                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
944                         do_batch_backend_process(oldbatchitems);
945                 } else {
946                         if (option_debug)
947                                 ast_log(LOG_DEBUG, "CDR multi-threaded batch processing begins now\n");
948                 }
949         }
950 }
951
952 static int submit_scheduled_batch(void *data)
953 {
954         ast_cdr_submit_batch(0);
955         /* manually reschedule from this point in time */
956         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
957         /* returning zero so the scheduler does not automatically reschedule */
958         return 0;
959 }
960
961 static void submit_unscheduled_batch(void)
962 {
963         /* this is okay since we are not being called from within the scheduler */
964         if (cdr_sched > -1)
965                 ast_sched_del(sched, cdr_sched);
966         /* schedule the submission to occur ASAP (1 ms) */
967         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
968         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
969         ast_mutex_lock(&cdr_pending_lock);
970         ast_cond_signal(&cdr_pending_cond);
971         ast_mutex_unlock(&cdr_pending_lock);
972 }
973
974 void ast_cdr_detach(struct ast_cdr *cdr)
975 {
976         struct ast_cdr_batch_item *newtail;
977         int curr;
978
979         /* maybe they disabled CDR stuff completely, so just drop it */
980         if (!enabled) {
981                 if (option_debug)
982                         ast_log(LOG_DEBUG, "Dropping CDR !\n");
983                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
984                 ast_cdr_free(cdr);
985                 return;
986         }
987
988         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
989         if (!batchmode) {
990                 post_cdr(cdr);
991                 ast_cdr_free(cdr);
992                 return;
993         }
994
995         /* otherwise, each CDR gets put into a batch list (at the end) */
996         if (option_debug)
997                 ast_log(LOG_DEBUG, "CDR detaching from this thread\n");
998
999         /* we'll need a new tail for every CDR */       
1000         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
1001                 post_cdr(cdr);
1002                 ast_cdr_free(cdr);
1003                 return;
1004         }
1005
1006         /* don't traverse a whole list (just keep track of the tail) */
1007         ast_mutex_lock(&cdr_batch_lock);
1008         if (!batch)
1009                 init_batch();
1010         if (!batch->head) {
1011                 /* new batch is empty, so point the head at the new tail */
1012                 batch->head = newtail;
1013         } else {
1014                 /* already got a batch with something in it, so just append a new tail */
1015                 batch->tail->next = newtail;
1016         }
1017         newtail->cdr = cdr;
1018         batch->tail = newtail;
1019         curr = batch->size++;
1020         ast_mutex_unlock(&cdr_batch_lock);
1021
1022         /* if we have enough stuff to post, then do it */
1023         if (curr >= (batchsize - 1))
1024                 submit_unscheduled_batch();
1025 }
1026
1027 static void *do_cdr(void *data)
1028 {
1029         struct timespec timeout;
1030         int schedms;
1031         int numevents = 0;
1032
1033         for(;;) {
1034                 struct timeval now = ast_tvnow();
1035                 schedms = ast_sched_wait(sched);
1036                 /* this shouldn't happen, but provide a 1 second default just in case */
1037                 if (schedms <= 0)
1038                         schedms = 1000;
1039                 timeout.tv_sec = now.tv_sec + (schedms / 1000);
1040                 timeout.tv_nsec = (now.tv_usec * 1000) + ((schedms % 1000) * 1000);
1041                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
1042                 ast_mutex_lock(&cdr_pending_lock);
1043                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
1044                 numevents = ast_sched_runq(sched);
1045                 ast_mutex_unlock(&cdr_pending_lock);
1046                 if (option_debug > 1)
1047                         ast_log(LOG_DEBUG, "Processed %d scheduled CDR batches from the run queue\n", numevents);
1048         }
1049
1050         return NULL;
1051 }
1052
1053 static int handle_cli_status(int fd, int argc, char *argv[])
1054 {
1055         struct ast_cdr_beitem *beitem=NULL;
1056         int cnt=0;
1057         long nextbatchtime=0;
1058
1059         if (argc > 2)
1060                 return RESULT_SHOWUSAGE;
1061
1062         ast_cli(fd, "CDR logging: %s\n", enabled ? "enabled" : "disabled");
1063         ast_cli(fd, "CDR mode: %s\n", batchmode ? "batch" : "simple");
1064         if (enabled) {
1065                 if (batchmode) {
1066                         if (batch)
1067                                 cnt = batch->size;
1068                         if (cdr_sched > -1)
1069                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
1070                         ast_cli(fd, "CDR safe shut down: %s\n", batchsafeshutdown ? "enabled" : "disabled");
1071                         ast_cli(fd, "CDR batch threading model: %s\n", batchscheduleronly ? "scheduler only" : "scheduler plus separate threads");
1072                         ast_cli(fd, "CDR current batch size: %d record%s\n", cnt, (cnt != 1) ? "s" : "");
1073                         ast_cli(fd, "CDR maximum batch size: %d record%s\n", batchsize, (batchsize != 1) ? "s" : "");
1074                         ast_cli(fd, "CDR maximum batch time: %d second%s\n", batchtime, (batchtime != 1) ? "s" : "");
1075                         ast_cli(fd, "CDR next scheduled batch processing time: %ld second%s\n", nextbatchtime, (nextbatchtime != 1) ? "s" : "");
1076                 }
1077                 AST_LIST_LOCK(&be_list);
1078                 AST_LIST_TRAVERSE(&be_list, beitem, list) {
1079                         ast_cli(fd, "CDR registered backend: %s\n", beitem->name);
1080                 }
1081                 AST_LIST_UNLOCK(&be_list);
1082         }
1083
1084         return 0;
1085 }
1086
1087 static int handle_cli_submit(int fd, int argc, char *argv[])
1088 {
1089         if (argc > 2)
1090                 return RESULT_SHOWUSAGE;
1091
1092         submit_unscheduled_batch();
1093         ast_cli(fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1094
1095         return 0;
1096 }
1097
1098 static struct ast_cli_entry cli_submit = {
1099         .cmda = { "cdr", "submit", NULL },
1100         .handler = handle_cli_submit,
1101         .summary = "Posts all pending batched CDR data",
1102         .usage =
1103         "Usage: cdr submit\n"
1104         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n"
1105 };
1106
1107 static struct ast_cli_entry cli_status = {
1108         .cmda = { "cdr", "status", NULL },
1109         .handler = handle_cli_status,
1110         .summary = "Display the CDR status",
1111         .usage =
1112         "Usage: cdr status\n"
1113         "       Displays the Call Detail Record engine system status.\n"
1114 };
1115
1116 static int do_reload(void)
1117 {
1118         struct ast_config *config;
1119         const char *enabled_value;
1120         const char *batched_value;
1121         const char *scheduleronly_value;
1122         const char *batchsafeshutdown_value;
1123         const char *size_value;
1124         const char *time_value;
1125         const char *end_before_h_value;
1126         int cfg_size;
1127         int cfg_time;
1128         int was_enabled;
1129         int was_batchmode;
1130         int res=0;
1131
1132         ast_mutex_lock(&cdr_batch_lock);
1133
1134         batchsize = BATCH_SIZE_DEFAULT;
1135         batchtime = BATCH_TIME_DEFAULT;
1136         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1137         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1138         was_enabled = enabled;
1139         was_batchmode = batchmode;
1140         enabled = 1;
1141         batchmode = 0;
1142
1143         /* don't run the next scheduled CDR posting while reloading */
1144         if (cdr_sched > -1)
1145                 ast_sched_del(sched, cdr_sched);
1146
1147         if ((config = ast_config_load("cdr.conf"))) {
1148                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1149                         enabled = ast_true(enabled_value);
1150                 }
1151                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1152                         batchmode = ast_true(batched_value);
1153                 }
1154                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1155                         batchscheduleronly = ast_true(scheduleronly_value);
1156                 }
1157                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1158                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1159                 }
1160                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1161                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1162                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1163                         else if (size_value < 0)
1164                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1165                         else
1166                                 batchsize = cfg_size;
1167                 }
1168                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1169                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1170                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1171                         else if (time_value < 0)
1172                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1173                         else
1174                                 batchtime = cfg_time;
1175                 }
1176                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1177                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_END_CDR_BEFORE_H_EXTEN);
1178         }
1179
1180         if (enabled && !batchmode) {
1181                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1182         } else if (enabled && batchmode) {
1183                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1184                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1185         } else {
1186                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1187         }
1188
1189         /* if this reload enabled the CDR batch mode, create the background thread
1190            if it does not exist */
1191         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1192                 ast_cond_init(&cdr_pending_cond, NULL);
1193                 if (ast_pthread_create(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1194                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1195                         ast_sched_del(sched, cdr_sched);
1196                 } else {
1197                         ast_cli_register(&cli_submit);
1198                         ast_register_atexit(ast_cdr_engine_term);
1199                         res = 0;
1200                 }
1201         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1202            kill it */
1203         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1204                 /* wake up the thread so it will exit */
1205                 pthread_cancel(cdr_thread);
1206                 pthread_kill(cdr_thread, SIGURG);
1207                 pthread_join(cdr_thread, NULL);
1208                 cdr_thread = AST_PTHREADT_NULL;
1209                 ast_cond_destroy(&cdr_pending_cond);
1210                 ast_cli_unregister(&cli_submit);
1211                 ast_unregister_atexit(ast_cdr_engine_term);
1212                 res = 0;
1213                 /* if leaving batch mode, then post the CDRs in the batch,
1214                    and don't reschedule, since we are stopping CDR logging */
1215                 if (!batchmode && was_batchmode) {
1216                         ast_cdr_engine_term();
1217                 }
1218         } else {
1219                 res = 0;
1220         }
1221
1222         ast_mutex_unlock(&cdr_batch_lock);
1223         ast_config_destroy(config);
1224
1225         return res;
1226 }
1227
1228 int ast_cdr_engine_init(void)
1229 {
1230         int res;
1231
1232         sched = sched_context_create();
1233         if (!sched) {
1234                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1235                 return -1;
1236         }
1237
1238         ast_cli_register(&cli_status);
1239
1240         res = do_reload();
1241         if (res) {
1242                 ast_mutex_lock(&cdr_batch_lock);
1243                 res = init_batch();
1244                 ast_mutex_unlock(&cdr_batch_lock);
1245         }
1246
1247         return res;
1248 }
1249
1250 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1251    hanging up channels, and then again, after the channel hangup timeout expires */
1252 void ast_cdr_engine_term(void)
1253 {
1254         ast_cdr_submit_batch(batchsafeshutdown);
1255 }
1256
1257 int ast_cdr_engine_reload(void)
1258 {
1259         return do_reload();
1260 }
1261