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