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