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