Remove unnecessary usleep() from a couple of module unload callbacks.
[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 <signal.h>
39
40 #include "asterisk/lock.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/cdr.h"
43 #include "asterisk/callerid.h"
44 #include "asterisk/manager.h"
45 #include "asterisk/causes.h"
46 #include "asterisk/linkedlists.h"
47 #include "asterisk/utils.h"
48 #include "asterisk/sched.h"
49 #include "asterisk/config.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/stringfields.h"
52
53 /*! Default AMA flag for billing records (CDR's) */
54 int ast_default_amaflags = AST_CDR_DOCUMENTATION;
55 char ast_default_accountcode[AST_MAX_ACCOUNT_CODE];
56
57 struct ast_cdr_beitem {
58         char name[20];
59         char desc[80];
60         ast_cdrbe be;
61         AST_RWLIST_ENTRY(ast_cdr_beitem) list;
62 };
63
64 static AST_RWLIST_HEAD_STATIC(be_list, ast_cdr_beitem);
65
66 struct ast_cdr_batch_item {
67         struct ast_cdr *cdr;
68         struct ast_cdr_batch_item *next;
69 };
70
71 static struct ast_cdr_batch {
72         int size;
73         struct ast_cdr_batch_item *head;
74         struct ast_cdr_batch_item *tail;
75 } *batch = NULL;
76
77 static struct sched_context *sched;
78 static int cdr_sched = -1;
79 static pthread_t cdr_thread = AST_PTHREADT_NULL;
80
81 #define BATCH_SIZE_DEFAULT 100
82 #define BATCH_TIME_DEFAULT 300
83 #define BATCH_SCHEDULER_ONLY_DEFAULT 0
84 #define BATCH_SAFE_SHUTDOWN_DEFAULT 1
85
86 static int enabled;             /*! Is the CDR subsystem enabled ? */
87 static int unanswered;
88 static int batchmode;
89 static int batchsize;
90 static int batchtime;
91 static int batchscheduleronly;
92 static int batchsafeshutdown;
93
94 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
95
96 /* these are used to wake up the CDR thread when there's work to do */
97 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
98 static ast_cond_t cdr_pending_cond;
99
100 int check_cdr_enabled()
101 {
102         return enabled;
103 }
104
105 /*! Register a CDR driver. Each registered CDR driver generates a CDR 
106         \return 0 on success, -1 on failure 
107 */
108 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
109 {
110         struct ast_cdr_beitem *i = NULL;
111
112         if (!name)
113                 return -1;
114
115         if (!be) {
116                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
117                 return -1;
118         }
119
120         AST_RWLIST_WRLOCK(&be_list);
121         AST_RWLIST_TRAVERSE(&be_list, i, list) {
122                 if (!strcasecmp(name, i->name)) {
123                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
124                         AST_RWLIST_UNLOCK(&be_list);
125                         return -1;
126                 }
127         }
128
129         if (!(i = ast_calloc(1, sizeof(*i))))   
130                 return -1;
131
132         i->be = be;
133         ast_copy_string(i->name, name, sizeof(i->name));
134         ast_copy_string(i->desc, desc, sizeof(i->desc));
135
136         AST_RWLIST_INSERT_HEAD(&be_list, i, list);
137         AST_RWLIST_UNLOCK(&be_list);
138
139         return 0;
140 }
141
142 /*! unregister a CDR driver */
143 void ast_cdr_unregister(const char *name)
144 {
145         struct ast_cdr_beitem *i = NULL;
146
147         AST_RWLIST_WRLOCK(&be_list);
148         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&be_list, i, list) {
149                 if (!strcasecmp(name, i->name)) {
150                         AST_RWLIST_REMOVE_CURRENT(list);
151                         break;
152                 }
153         }
154         AST_RWLIST_TRAVERSE_SAFE_END;
155         AST_RWLIST_UNLOCK(&be_list);
156
157         if (i) {
158                 ast_verb(2, "Unregistered '%s' CDR backend\n", name);
159                 ast_free(i);
160         }
161 }
162
163 int ast_cdr_isset_unanswered(void)
164 {
165         return unanswered;
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 when, const char *fmt, char *buf, int bufsize)
208 {
209         if (fmt == NULL) {      /* raw mode */
210                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
211         } else {
212                 if (when.tv_sec) {
213                         struct ast_tm tm;
214                         
215                         ast_localtime(&when, &tm, NULL);
216                         ast_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 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
258         else if (!strcasecmp(name, "billsec"))
259                 snprintf(workspace, workspacelen, "%ld", cdr->billsec || cdr->answer.tv_sec == 0 ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
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 * const 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                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
318                         continue;
319                 headp = &cdr->varshead;
320                 AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
321                         if (!strcasecmp(ast_var_name(newvariable), name)) {
322                                 /* there is already such a variable, delete it */
323                                 AST_LIST_REMOVE_CURRENT(entries);
324                                 ast_var_delete(newvariable);
325                                 break;
326                         }
327                 }
328                 AST_LIST_TRAVERSE_SAFE_END;
329                 
330                 if (value) {
331                         newvariable = ast_var_assign(name, value);
332                         AST_LIST_INSERT_HEAD(headp, newvariable, entries);
333                 }
334         }
335
336         return 0;
337 }
338
339 int ast_cdr_copy_vars(struct ast_cdr *to_cdr, struct ast_cdr *from_cdr)
340 {
341         struct ast_var_t *variables, *newvariable = NULL;
342         struct varshead *headpa, *headpb;
343         const char *var, *val;
344         int x = 0;
345
346         if (!to_cdr || !from_cdr) /* don't die if one of the pointers is null */
347                 return 0;
348
349         headpa = &from_cdr->varshead;
350         headpb = &to_cdr->varshead;
351
352         AST_LIST_TRAVERSE(headpa,variables,entries) {
353                 if (variables &&
354                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
355                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
356                         newvariable = ast_var_assign(var, val);
357                         AST_LIST_INSERT_HEAD(headpb, newvariable, entries);
358                         x++;
359                 }
360         }
361
362         return x;
363 }
364
365 int ast_cdr_serialize_variables(struct ast_cdr *cdr, struct ast_str **buf, char delim, char sep, int recur) 
366 {
367         struct ast_var_t *variables;
368         const char *var, *val;
369         char *tmp;
370         char workspace[256];
371         int total = 0, x = 0, i;
372
373         ast_str_reset(*buf);
374
375         for (; cdr; cdr = recur ? cdr->next : NULL) {
376                 if (++x > 1)
377                         ast_str_append(buf, 0, "\n");
378
379                 AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
380                         if (variables &&
381                             (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
382                             !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
383                                 if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, val, sep) < 0) {
384                                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
385                                         break;
386                                 } else
387                                         total++;
388                         } else 
389                                 break;
390                 }
391
392                 for (i = 0; cdr_readonly_vars[i]; i++) {
393                         workspace[0] = 0; /* null out the workspace, because the cdr_get_tv() won't write anything if time is NULL, so you get old vals */
394                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
395                         if (!tmp)
396                                 continue;
397                         
398                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep) < 0) {
399                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
400                                 break;
401                         } else
402                                 total++;
403                 }
404         }
405
406         return total;
407 }
408
409
410 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
411 {
412
413         /* clear variables */
414         for (; cdr; cdr = recur ? cdr->next : NULL) {
415                 struct ast_var_t *vardata;
416                 struct varshead *headp = &cdr->varshead;
417                 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
418                         ast_var_delete(vardata);
419         }
420 }
421
422 /*! \brief  print a warning if cdr already posted */
423 static void check_post(struct ast_cdr *cdr)
424 {
425         if (!cdr)
426                 return;
427         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
428                 ast_log(LOG_NOTICE, "CDR on channel '%s' already posted\n", S_OR(cdr->channel, "<unknown>"));
429 }
430
431 void ast_cdr_free(struct ast_cdr *cdr)
432 {
433
434         while (cdr) {
435                 struct ast_cdr *next = cdr->next;
436
437                 ast_cdr_free_vars(cdr, 0);
438                 ast_free(cdr);
439                 cdr = next;
440         }
441 }
442
443 /*! \brief the same as a cdr_free call, only with no checks; just get rid of it */
444 void ast_cdr_discard(struct ast_cdr *cdr)
445 {
446         while (cdr) {
447                 struct ast_cdr *next = cdr->next;
448
449                 ast_cdr_free_vars(cdr, 0);
450                 ast_free(cdr);
451                 cdr = next;
452         }
453 }
454
455 struct ast_cdr *ast_cdr_alloc(void)
456 {
457         struct ast_cdr *x;
458         x = ast_calloc(1, sizeof(*x));
459         if (!x)
460                 ast_log(LOG_ERROR,"Allocation Failure for a CDR!\n");
461         return x;
462 }
463
464 static void cdr_merge_vars(struct ast_cdr *to, struct ast_cdr *from)
465 {
466         struct ast_var_t *variablesfrom,*variablesto;
467         struct varshead *headpfrom = &to->varshead;
468         struct varshead *headpto = &from->varshead;
469         AST_LIST_TRAVERSE_SAFE_BEGIN(headpfrom, variablesfrom, entries) {
470                 /* for every var in from, stick it in to */
471                 const char *fromvarname, *fromvarval;
472                 const char *tovarname = NULL, *tovarval = NULL;
473                 fromvarname = ast_var_name(variablesfrom);
474                 fromvarval = ast_var_value(variablesfrom);
475                 tovarname = 0;
476
477                 /* now, quick see if that var is in the 'to' cdr already */
478                 AST_LIST_TRAVERSE(headpto, variablesto, entries) {
479
480                         /* now, quick see if that var is in the 'to' cdr already */
481                         if ( strcasecmp(fromvarname, ast_var_name(variablesto)) == 0 ) {
482                                 tovarname = ast_var_name(variablesto);
483                                 tovarval = ast_var_value(variablesto);
484                                 break;
485                         }
486                 }
487                 if (tovarname && strcasecmp(fromvarval,tovarval) != 0) {  /* this message here to see how irritating the userbase finds it */
488                         ast_log(LOG_NOTICE, "Merging CDR's: variable %s value %s dropped in favor of value %s\n", tovarname, fromvarval, tovarval);
489                         continue;
490                 } else if (tovarname && strcasecmp(fromvarval,tovarval) == 0) /* if they are the same, the job is done */
491                         continue;
492
493                 /* rip this var out of the from cdr, and stick it in the to cdr */
494                 AST_LIST_MOVE_CURRENT(headpto, entries);
495         }
496         AST_LIST_TRAVERSE_SAFE_END;
497 }
498
499 void ast_cdr_merge(struct ast_cdr *to, struct ast_cdr *from)
500 {
501         struct ast_cdr *zcdr;
502         struct ast_cdr *lto = NULL;
503         struct ast_cdr *lfrom = NULL;
504         int discard_from = 0;
505         
506         if (!to || !from)
507                 return;
508
509         /* don't merge into locked CDR's -- it's bad business */
510         if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
511                 zcdr = to; /* safety valve? */
512                 while (to->next) {
513                         lto = to;
514                         to = to->next;
515                 }
516                 
517                 if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
518                         ast_log(LOG_WARNING, "Merging into locked CDR... no choice.");
519                         to = zcdr; /* safety-- if all there are is locked CDR's, then.... ?? */
520                         lto = NULL;
521                 }
522         }
523
524         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED)) {
525                 struct ast_cdr *llfrom = NULL;
526                 discard_from = 1;
527                 if (lto) {
528                         /* insert the from stuff after lto */
529                         lto->next = from;
530                         lfrom = from;
531                         while (lfrom && lfrom->next) {
532                                 if (!lfrom->next->next)
533                                         llfrom = lfrom;
534                                 lfrom = lfrom->next; 
535                         }
536                         /* rip off the last entry and put a copy of the to at the end */
537                         llfrom->next = to;
538                         from = lfrom;
539                 } else {
540                         /* save copy of the current *to cdr */
541                         struct ast_cdr tcdr;
542                         memcpy(&tcdr, to, sizeof(tcdr));
543                         /* copy in the locked from cdr */
544                         memcpy(to, from, sizeof(*to));
545                         lfrom = from;
546                         while (lfrom && lfrom->next) {
547                                 if (!lfrom->next->next)
548                                         llfrom = lfrom;
549                                 lfrom = lfrom->next; 
550                         }
551                         from->next = NULL;
552                         /* rip off the last entry and put a copy of the to at the end */
553                         if (llfrom == from)
554                                 to = to->next = ast_cdr_dup(&tcdr);
555                         else
556                                 to = llfrom->next = ast_cdr_dup(&tcdr);
557                         from = lfrom;
558                 }
559         }
560         
561         if (!ast_tvzero(from->start)) {
562                 if (!ast_tvzero(to->start)) {
563                         if (ast_tvcmp(to->start, from->start) > 0 ) {
564                                 to->start = from->start; /* use the earliest time */
565                                 from->start = ast_tv(0,0); /* we actively "steal" these values */
566                         }
567                         /* else nothing to do */
568                 } else {
569                         to->start = from->start;
570                         from->start = ast_tv(0,0); /* we actively "steal" these values */
571                 }
572         }
573         if (!ast_tvzero(from->answer)) {
574                 if (!ast_tvzero(to->answer)) {
575                         if (ast_tvcmp(to->answer, from->answer) > 0 ) {
576                                 to->answer = from->answer; /* use the earliest time */
577                                 from->answer = ast_tv(0,0); /* we actively "steal" these values */
578                         }
579                         /* we got the earliest answer time, so we'll settle for that? */
580                 } else {
581                         to->answer = from->answer;
582                         from->answer = ast_tv(0,0); /* we actively "steal" these values */
583                 }
584         }
585         if (!ast_tvzero(from->end)) {
586                 if (!ast_tvzero(to->end)) {
587                         if (ast_tvcmp(to->end, from->end) < 0 ) {
588                                 to->end = from->end; /* use the latest time */
589                                 from->end = ast_tv(0,0); /* we actively "steal" these values */
590                                 to->duration = to->end.tv_sec - to->start.tv_sec;  /* don't forget to update the duration, billsec, when we set end */
591                                 to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
592                         }
593                         /* else, nothing to do */
594                 } else {
595                         to->end = from->end;
596                         from->end = ast_tv(0,0); /* we actively "steal" these values */
597                         to->duration = to->end.tv_sec - to->start.tv_sec;
598                         to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
599                 }
600         }
601         if (to->disposition < from->disposition) {
602                 to->disposition = from->disposition;
603                 from->disposition = AST_CDR_NOANSWER;
604         }
605         if (ast_strlen_zero(to->lastapp) && !ast_strlen_zero(from->lastapp)) {
606                 ast_copy_string(to->lastapp, from->lastapp, sizeof(to->lastapp));
607                 from->lastapp[0] = 0; /* theft */
608         }
609         if (ast_strlen_zero(to->lastdata) && !ast_strlen_zero(from->lastdata)) {
610                 ast_copy_string(to->lastdata, from->lastdata, sizeof(to->lastdata));
611                 from->lastdata[0] = 0; /* theft */
612         }
613         if (ast_strlen_zero(to->dcontext) && !ast_strlen_zero(from->dcontext)) {
614                 ast_copy_string(to->dcontext, from->dcontext, sizeof(to->dcontext));
615                 from->dcontext[0] = 0; /* theft */
616         }
617         if (ast_strlen_zero(to->dstchannel) && !ast_strlen_zero(from->dstchannel)) {
618                 ast_copy_string(to->dstchannel, from->dstchannel, sizeof(to->dstchannel));
619                 from->dstchannel[0] = 0; /* theft */
620         }
621         if (!ast_strlen_zero(from->channel) && (ast_strlen_zero(to->channel) || !strncasecmp(from->channel, "Agent/", 6))) {
622                 ast_copy_string(to->channel, from->channel, sizeof(to->channel));
623                 from->channel[0] = 0; /* theft */
624         }
625         if (ast_strlen_zero(to->src) && !ast_strlen_zero(from->src)) {
626                 ast_copy_string(to->src, from->src, sizeof(to->src));
627                 from->src[0] = 0; /* theft */
628         }
629         if (ast_strlen_zero(to->clid) && !ast_strlen_zero(from->clid)) {
630                 ast_copy_string(to->clid, from->clid, sizeof(to->clid));
631                 from->clid[0] = 0; /* theft */
632         }
633         if (ast_strlen_zero(to->dst) && !ast_strlen_zero(from->dst)) {
634                 ast_copy_string(to->dst, from->dst, sizeof(to->dst));
635                 from->dst[0] = 0; /* theft */
636         }
637         if (!to->amaflags)
638                 to->amaflags = AST_CDR_DOCUMENTATION;
639         if (!from->amaflags)
640                 from->amaflags = AST_CDR_DOCUMENTATION; /* make sure both amaflags are set to something (DOC is default) */
641         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (to->amaflags == AST_CDR_DOCUMENTATION && from->amaflags != AST_CDR_DOCUMENTATION)) {
642                 to->amaflags = from->amaflags;
643         }
644         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->accountcode) && !ast_strlen_zero(from->accountcode))) {
645                 ast_copy_string(to->accountcode, from->accountcode, sizeof(to->accountcode));
646         }
647         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->userfield) && !ast_strlen_zero(from->userfield))) {
648                 ast_copy_string(to->userfield, from->userfield, sizeof(to->userfield));
649         }
650         /* flags, varsead, ? */
651         cdr_merge_vars(from, to);
652
653         if (ast_test_flag(from, AST_CDR_FLAG_KEEP_VARS))
654                 ast_set_flag(to, AST_CDR_FLAG_KEEP_VARS);
655         if (ast_test_flag(from, AST_CDR_FLAG_POSTED))
656                 ast_set_flag(to, AST_CDR_FLAG_POSTED);
657         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED))
658                 ast_set_flag(to, AST_CDR_FLAG_LOCKED);
659         if (ast_test_flag(from, AST_CDR_FLAG_CHILD))
660                 ast_set_flag(to, AST_CDR_FLAG_CHILD);
661         if (ast_test_flag(from, AST_CDR_FLAG_POST_DISABLED))
662                 ast_set_flag(to, AST_CDR_FLAG_POST_DISABLED);
663
664         /* last, but not least, we need to merge any forked CDRs to the 'to' cdr */
665         while (from->next) {
666                 /* just rip 'em off the 'from' and insert them on the 'to' */
667                 zcdr = from->next;
668                 from->next = zcdr->next;
669                 zcdr->next = NULL;
670                 /* zcdr is now ripped from the current list; */
671                 ast_cdr_append(to, zcdr);
672         }
673         if (discard_from)
674                 ast_cdr_discard(from);
675 }
676
677 void ast_cdr_start(struct ast_cdr *cdr)
678 {
679         char *chan; 
680
681         for (; cdr; cdr = cdr->next) {
682                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
683                         chan = S_OR(cdr->channel, "<unknown>");
684                         check_post(cdr);
685                         cdr->start = ast_tvnow();
686                 }
687         }
688 }
689
690 void ast_cdr_answer(struct ast_cdr *cdr)
691 {
692
693         for (; cdr; cdr = cdr->next) {
694                 if (ast_test_flag(cdr, AST_CDR_FLAG_ANSLOCKED)) 
695                         continue;
696                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
697                         continue;
698                 check_post(cdr);
699                 if (cdr->disposition < AST_CDR_ANSWERED)
700                         cdr->disposition = AST_CDR_ANSWERED;
701                 if (ast_tvzero(cdr->answer))
702                         cdr->answer = ast_tvnow();
703         }
704 }
705
706 void ast_cdr_busy(struct ast_cdr *cdr)
707 {
708
709         for (; cdr; cdr = cdr->next) {
710                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
711                         check_post(cdr);
712                         if (cdr->disposition < AST_CDR_BUSY)
713                                 cdr->disposition = AST_CDR_BUSY;
714                 }
715         }
716 }
717
718 void ast_cdr_failed(struct ast_cdr *cdr)
719 {
720         for (; cdr; cdr = cdr->next) {
721                 check_post(cdr);
722                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
723                         check_post(cdr);
724                         if (cdr->disposition < AST_CDR_FAILED)
725                                 cdr->disposition = AST_CDR_FAILED;
726                 }
727         }
728 }
729
730 void ast_cdr_noanswer(struct ast_cdr *cdr)
731 {
732         char *chan; 
733
734         while (cdr) {
735                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
736                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
737                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
738                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
739                         if (cdr->disposition < AST_CDR_NOANSWER)
740                                 cdr->disposition = AST_CDR_NOANSWER;
741                 }
742                 cdr = cdr->next;
743         }
744 }
745
746 /* everywhere ast_cdr_disposition is called, it will call ast_cdr_failed() 
747    if ast_cdr_disposition returns a non-zero value */
748
749 int ast_cdr_disposition(struct ast_cdr *cdr, int cause)
750 {
751         int res = 0;
752
753         for (; cdr; cdr = cdr->next) {
754                 switch (cause) {  /* handle all the non failure, busy cases, return 0 not to set disposition,
755                                                         return -1 to set disposition to FAILED */
756                 case AST_CAUSE_BUSY:
757                         ast_cdr_busy(cdr);
758                         break;
759                 case AST_CAUSE_NO_ANSWER:
760                         ast_cdr_noanswer(cdr);
761                         break;
762                 case AST_CAUSE_NORMAL:
763                         break;
764                 default:
765                         res = -1;
766                 }
767         }
768         return res;
769 }
770
771 void ast_cdr_setdestchan(struct ast_cdr *cdr, const char *chann)
772 {
773         for (; cdr; cdr = cdr->next) {
774                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
775                         check_post(cdr);
776                         ast_copy_string(cdr->dstchannel, chann, sizeof(cdr->dstchannel));
777                 }
778         }
779 }
780
781 void ast_cdr_setapp(struct ast_cdr *cdr, const char *app, const char *data)
782 {
783
784         for (; cdr; cdr = cdr->next) {
785                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
786                         check_post(cdr);
787                         ast_copy_string(cdr->lastapp, S_OR(app, ""), sizeof(cdr->lastapp));
788                         ast_copy_string(cdr->lastdata, S_OR(data, ""), sizeof(cdr->lastdata));
789                 }
790         }
791 }
792
793 void ast_cdr_setanswer(struct ast_cdr *cdr, struct timeval t)
794 {
795
796         for (; cdr; cdr = cdr->next) {
797                 if (ast_test_flag(cdr, AST_CDR_FLAG_ANSLOCKED))
798                         continue;
799                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
800                         continue;
801                 check_post(cdr);
802                 cdr->answer = t;
803         }
804 }
805
806 void ast_cdr_setdisposition(struct ast_cdr *cdr, long int disposition)
807 {
808
809         for (; cdr; cdr = cdr->next) {
810                 if (ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
811                         continue;
812                 check_post(cdr);
813                 cdr->disposition = disposition;
814         }
815 }
816
817 /* set cid info for one record */
818 static void set_one_cid(struct ast_cdr *cdr, struct ast_channel *c)
819 {
820         /* Grab source from ANI or normal Caller*ID */
821         const char *num = S_OR(c->cid.cid_ani, c->cid.cid_num);
822         if (!cdr)
823                 return;
824         if (!ast_strlen_zero(c->cid.cid_name)) {
825                 if (!ast_strlen_zero(num))      /* both name and number */
826                         snprintf(cdr->clid, sizeof(cdr->clid), "\"%s\" <%s>", c->cid.cid_name, num);
827                 else                            /* only name */
828                         ast_copy_string(cdr->clid, c->cid.cid_name, sizeof(cdr->clid));
829         } else if (!ast_strlen_zero(num)) {     /* only number */
830                 ast_copy_string(cdr->clid, num, sizeof(cdr->clid));
831         } else {                                /* nothing known */
832                 cdr->clid[0] = '\0';
833         }
834         ast_copy_string(cdr->src, S_OR(num, ""), sizeof(cdr->src));
835
836 }
837 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
838 {
839         for (; cdr; cdr = cdr->next) {
840                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
841                         set_one_cid(cdr, c);
842         }
843         return 0;
844 }
845
846 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
847 {
848         char *chan;
849
850         for ( ; cdr ; cdr = cdr->next) {
851                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
852                         chan = S_OR(cdr->channel, "<unknown>");
853                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
854                         set_one_cid(cdr, c);
855
856                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NOANSWER;
857                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
858                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
859                         /* Destination information */
860                         ast_copy_string(cdr->dst, S_OR(c->macroexten,c->exten), sizeof(cdr->dst));
861                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext,c->context), sizeof(cdr->dcontext));
862                         /* Unique call identifier */
863                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
864                 }
865         }
866         return 0;
867 }
868
869 /* Three routines were "fixed" via 10668, and later shown that 
870    users were depending on this behavior. ast_cdr_end,
871    ast_cdr_setvar and ast_cdr_answer are the three routines.
872    While most of the other routines would not touch 
873    LOCKED cdr's, these three routines were designed to
874    operate on locked CDR's as a matter of course.
875    I now appreciate how this plays with the ForkCDR app,
876    which forms these cdr chains in the first place. 
877    cdr_end is pretty key: all cdrs created are closed
878    together. They only vary by start time. Arithmetically,
879    users can calculate the subintervals they wish to track. */
880
881 void ast_cdr_end(struct ast_cdr *cdr)
882 {
883         for ( ; cdr ; cdr = cdr->next) {
884                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
885                         continue;
886                 check_post(cdr);
887                 if (ast_tvzero(cdr->end))
888                         cdr->end = ast_tvnow();
889                 if (ast_tvzero(cdr->start)) {
890                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", S_OR(cdr->channel, "<unknown>"));
891                         cdr->disposition = AST_CDR_FAILED;
892                 } else
893                         cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
894                 if (ast_tvzero(cdr->answer)) {
895                         if (cdr->disposition == AST_CDR_ANSWERED) {
896                                 ast_log(LOG_WARNING, "CDR on channel '%s' has no answer time but is 'ANSWERED'\n", S_OR(cdr->channel, "<unknown>"));
897                                 cdr->disposition = AST_CDR_FAILED;
898                         }
899                 } else {
900                         cdr->billsec = cdr->end.tv_sec - cdr->answer.tv_sec;
901                         if (ast_test_flag(&ast_options, AST_OPT_FLAG_INITIATED_SECONDS))
902                                 cdr->billsec += cdr->end.tv_usec > cdr->answer.tv_usec ? 1 : 0;
903                 }
904         }
905 }
906
907 char *ast_cdr_disp2str(int disposition)
908 {
909         switch (disposition) {
910         case AST_CDR_NULL:
911                 return "NO ANSWER"; /* by default, for backward compatibility */
912         case AST_CDR_NOANSWER:
913                 return "NO ANSWER";
914         case AST_CDR_FAILED:
915                 return "FAILED";                
916         case AST_CDR_BUSY:
917                 return "BUSY";          
918         case AST_CDR_ANSWERED:
919                 return "ANSWERED";
920         }
921         return "UNKNOWN";
922 }
923
924 /*! Converts AMA flag to printable string */
925 char *ast_cdr_flags2str(int flag)
926 {
927         switch (flag) {
928         case AST_CDR_OMIT:
929                 return "OMIT";
930         case AST_CDR_BILLING:
931                 return "BILLING";
932         case AST_CDR_DOCUMENTATION:
933                 return "DOCUMENTATION";
934         }
935         return "Unknown";
936 }
937
938 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
939 {
940         struct ast_cdr *cdr = chan->cdr;
941         char buf[BUFSIZ/2] = "";
942         if (!ast_strlen_zero(chan->accountcode))
943                 ast_copy_string(buf, chan->accountcode, sizeof(buf));
944
945         ast_string_field_set(chan, accountcode, account);
946         for ( ; cdr ; cdr = cdr->next) {
947                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
948                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
949                 }
950         }
951
952         /* Signal change of account code to manager */
953         manager_event(EVENT_FLAG_CALL, "NewAccountCode", "Channel: %s\r\nUniqueid: %s\r\nAccountCode: %s\r\nOldAccountCode: %s\r\n", chan->name, chan->uniqueid, chan->accountcode, buf);
954         return 0;
955 }
956
957 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
958 {
959         struct ast_cdr *cdr;
960         int newflag = ast_cdr_amaflags2int(flag);
961         if (newflag) {
962                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
963                         if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
964                                 cdr->amaflags = newflag;
965                         }
966                 }
967         }
968
969         return 0;
970 }
971
972 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
973 {
974         struct ast_cdr *cdr = chan->cdr;
975
976         for ( ; cdr ; cdr = cdr->next) {
977                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
978                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
979         }
980
981         return 0;
982 }
983
984 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
985 {
986         struct ast_cdr *cdr = chan->cdr;
987
988         for ( ; cdr ; cdr = cdr->next) {
989                 int len = strlen(cdr->userfield);
990
991                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
992                         ast_copy_string(cdr->userfield + len, userfield, sizeof(cdr->userfield) - len);
993         }
994
995         return 0;
996 }
997
998 int ast_cdr_update(struct ast_channel *c)
999 {
1000         struct ast_cdr *cdr = c->cdr;
1001
1002         for ( ; cdr ; cdr = cdr->next) {
1003                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1004                         set_one_cid(cdr, c);
1005
1006                         /* Copy account code et-al */   
1007                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
1008                         
1009                         /* Destination information */ /* XXX privilege macro* ? */
1010                         ast_copy_string(cdr->dst, S_OR(c->macroexten, c->exten), sizeof(cdr->dst));
1011                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext, c->context), sizeof(cdr->dcontext));
1012                 }
1013         }
1014
1015         return 0;
1016 }
1017
1018 int ast_cdr_amaflags2int(const char *flag)
1019 {
1020         if (!strcasecmp(flag, "default"))
1021                 return 0;
1022         if (!strcasecmp(flag, "omit"))
1023                 return AST_CDR_OMIT;
1024         if (!strcasecmp(flag, "billing"))
1025                 return AST_CDR_BILLING;
1026         if (!strcasecmp(flag, "documentation"))
1027                 return AST_CDR_DOCUMENTATION;
1028         return -1;
1029 }
1030
1031 static void post_cdr(struct ast_cdr *cdr)
1032 {
1033         char *chan;
1034         struct ast_cdr_beitem *i;
1035
1036         for ( ; cdr ; cdr = cdr->next) {
1037                 if (!unanswered && cdr->disposition < AST_CDR_ANSWERED && (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
1038                         /* For people, who don't want to see unanswered single-channel events */
1039                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1040                         continue;
1041                 }
1042
1043                 /* don't post CDRs that are for dialed channels unless those
1044                  * channels were originated from asterisk (pbx_spool, manager,
1045                  * cli) */
1046                 if (ast_test_flag(cdr, AST_CDR_FLAG_DIALED) && !ast_test_flag(cdr, AST_CDR_FLAG_ORIGINATED)) {
1047                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1048                         continue;
1049                 }
1050
1051                 chan = S_OR(cdr->channel, "<unknown>");
1052                 check_post(cdr);
1053                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
1054                 if (ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
1055                         continue;
1056                 AST_RWLIST_RDLOCK(&be_list);
1057                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
1058                         i->be(cdr);
1059                 }
1060                 AST_RWLIST_UNLOCK(&be_list);
1061         }
1062 }
1063
1064 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
1065 {
1066         struct ast_cdr *duplicate;
1067         struct ast_flags flags = { 0 };
1068
1069         if (_flags)
1070                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
1071
1072         for ( ; cdr ; cdr = cdr->next) {
1073                 /* Detach if post is requested */
1074                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1075                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
1076                                 ast_cdr_end(cdr);
1077                                 if ((duplicate = ast_cdr_dup(cdr))) {
1078                                         ast_cdr_detach(duplicate);
1079                                 }
1080                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
1081                         }
1082
1083                         /* enable CDR only */
1084                         if (ast_test_flag(&flags, AST_CDR_FLAG_POST_ENABLE)) {
1085                                 ast_clear_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1086                                 continue;
1087                         }
1088
1089                         /* clear variables */
1090                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
1091                                 ast_cdr_free_vars(cdr, 0);
1092                         }
1093
1094                         /* Reset to initial state */
1095                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
1096                         memset(&cdr->start, 0, sizeof(cdr->start));
1097                         memset(&cdr->end, 0, sizeof(cdr->end));
1098                         memset(&cdr->answer, 0, sizeof(cdr->answer));
1099                         cdr->billsec = 0;
1100                         cdr->duration = 0;
1101                         ast_cdr_start(cdr);
1102                         cdr->disposition = AST_CDR_NOANSWER;
1103                 }
1104         }
1105 }
1106
1107 void ast_cdr_specialized_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
1108 {
1109         struct ast_flags flags = { 0 };
1110
1111         if (_flags)
1112                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
1113         
1114         /* Reset to initial state */
1115         if (ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED)) { /* But do NOT lose the NoCDR() setting */
1116                 ast_clear_flag(cdr, AST_FLAGS_ALL);     
1117                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1118         } else {
1119                 ast_clear_flag(cdr, AST_FLAGS_ALL);     
1120         }
1121         
1122         memset(&cdr->start, 0, sizeof(cdr->start));
1123         memset(&cdr->end, 0, sizeof(cdr->end));
1124         memset(&cdr->answer, 0, sizeof(cdr->answer));
1125         cdr->billsec = 0;
1126         cdr->duration = 0;
1127         ast_cdr_start(cdr);
1128         cdr->disposition = AST_CDR_NULL;
1129 }
1130
1131 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
1132 {
1133         struct ast_cdr *ret;
1134
1135         if (cdr) {
1136                 ret = cdr;
1137
1138                 while (cdr->next)
1139                         cdr = cdr->next;
1140                 cdr->next = newcdr;
1141         } else {
1142                 ret = newcdr;
1143         }
1144
1145         return ret;
1146 }
1147
1148 /*! \note Don't call without cdr_batch_lock */
1149 static void reset_batch(void)
1150 {
1151         batch->size = 0;
1152         batch->head = NULL;
1153         batch->tail = NULL;
1154 }
1155
1156 /*! \note Don't call without cdr_batch_lock */
1157 static int init_batch(void)
1158 {
1159         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
1160         if (!(batch = ast_malloc(sizeof(*batch))))
1161                 return -1;
1162
1163         reset_batch();
1164
1165         return 0;
1166 }
1167
1168 static void *do_batch_backend_process(void *data)
1169 {
1170         struct ast_cdr_batch_item *processeditem;
1171         struct ast_cdr_batch_item *batchitem = data;
1172
1173         /* Push each CDR into storage mechanism(s) and free all the memory */
1174         while (batchitem) {
1175                 post_cdr(batchitem->cdr);
1176                 ast_cdr_free(batchitem->cdr);
1177                 processeditem = batchitem;
1178                 batchitem = batchitem->next;
1179                 ast_free(processeditem);
1180         }
1181
1182         return NULL;
1183 }
1184
1185 void ast_cdr_submit_batch(int do_shutdown)
1186 {
1187         struct ast_cdr_batch_item *oldbatchitems = NULL;
1188         pthread_t batch_post_thread = AST_PTHREADT_NULL;
1189
1190         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
1191         if (!batch || !batch->head)
1192                 return;
1193
1194         /* move the old CDRs aside, and prepare a new CDR batch */
1195         ast_mutex_lock(&cdr_batch_lock);
1196         oldbatchitems = batch->head;
1197         reset_batch();
1198         ast_mutex_unlock(&cdr_batch_lock);
1199
1200         /* if configured, spawn a new thread to post these CDRs,
1201            also try to save as much as possible if we are shutting down safely */
1202         if (batchscheduleronly || do_shutdown) {
1203                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
1204                 do_batch_backend_process(oldbatchitems);
1205         } else {
1206                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
1207                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
1208                         do_batch_backend_process(oldbatchitems);
1209                 } else {
1210                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
1211                 }
1212         }
1213 }
1214
1215 static int submit_scheduled_batch(const void *data)
1216 {
1217         ast_cdr_submit_batch(0);
1218         /* manually reschedule from this point in time */
1219         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1220         /* returning zero so the scheduler does not automatically reschedule */
1221         return 0;
1222 }
1223
1224 static void submit_unscheduled_batch(void)
1225 {
1226         /* this is okay since we are not being called from within the scheduler */
1227         AST_SCHED_DEL(sched, cdr_sched);
1228         /* schedule the submission to occur ASAP (1 ms) */
1229         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
1230         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
1231         ast_mutex_lock(&cdr_pending_lock);
1232         ast_cond_signal(&cdr_pending_cond);
1233         ast_mutex_unlock(&cdr_pending_lock);
1234 }
1235
1236 void ast_cdr_detach(struct ast_cdr *cdr)
1237 {
1238         struct ast_cdr_batch_item *newtail;
1239         int curr;
1240
1241         if (!cdr)
1242                 return;
1243
1244         /* maybe they disabled CDR stuff completely, so just drop it */
1245         if (!enabled) {
1246                 ast_debug(1, "Dropping CDR !\n");
1247                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1248                 ast_cdr_free(cdr);
1249                 return;
1250         }
1251
1252         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
1253         if (!batchmode) {
1254                 post_cdr(cdr);
1255                 ast_cdr_free(cdr);
1256                 return;
1257         }
1258
1259         /* otherwise, each CDR gets put into a batch list (at the end) */
1260         ast_debug(1, "CDR detaching from this thread\n");
1261
1262         /* we'll need a new tail for every CDR */
1263         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
1264                 post_cdr(cdr);
1265                 ast_cdr_free(cdr);
1266                 return;
1267         }
1268
1269         /* don't traverse a whole list (just keep track of the tail) */
1270         ast_mutex_lock(&cdr_batch_lock);
1271         if (!batch)
1272                 init_batch();
1273         if (!batch->head) {
1274                 /* new batch is empty, so point the head at the new tail */
1275                 batch->head = newtail;
1276         } else {
1277                 /* already got a batch with something in it, so just append a new tail */
1278                 batch->tail->next = newtail;
1279         }
1280         newtail->cdr = cdr;
1281         batch->tail = newtail;
1282         curr = batch->size++;
1283         ast_mutex_unlock(&cdr_batch_lock);
1284
1285         /* if we have enough stuff to post, then do it */
1286         if (curr >= (batchsize - 1))
1287                 submit_unscheduled_batch();
1288 }
1289
1290 static void *do_cdr(void *data)
1291 {
1292         struct timespec timeout;
1293         int schedms;
1294         int numevents = 0;
1295
1296         for (;;) {
1297                 struct timeval now;
1298                 schedms = ast_sched_wait(sched);
1299                 /* this shouldn't happen, but provide a 1 second default just in case */
1300                 if (schedms <= 0)
1301                         schedms = 1000;
1302                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
1303                 timeout.tv_sec = now.tv_sec;
1304                 timeout.tv_nsec = now.tv_usec * 1000;
1305                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
1306                 ast_mutex_lock(&cdr_pending_lock);
1307                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
1308                 numevents = ast_sched_runq(sched);
1309                 ast_mutex_unlock(&cdr_pending_lock);
1310                 ast_debug(2, "Processed %d scheduled CDR batches from the run queue\n", numevents);
1311         }
1312
1313         return NULL;
1314 }
1315
1316 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1317 {
1318         struct ast_cdr_beitem *beitem=NULL;
1319         int cnt=0;
1320         long nextbatchtime=0;
1321
1322         switch (cmd) {
1323         case CLI_INIT:
1324                 e->command = "cdr show status";
1325                 e->usage = 
1326                         "Usage: cdr show status\n"
1327                         "       Displays the Call Detail Record engine system status.\n";
1328                 return NULL;
1329         case CLI_GENERATE:
1330                 return NULL;
1331         }
1332
1333         if (a->argc > 3)
1334                 return CLI_SHOWUSAGE;
1335
1336         ast_cli(a->fd, "\n");
1337         ast_cli(a->fd, "Call Detail Record (CDR) settings\n");
1338         ast_cli(a->fd, "----------------------------------\n");
1339         ast_cli(a->fd, "  Logging:                    %s\n", enabled ? "Enabled" : "Disabled");
1340         ast_cli(a->fd, "  Mode:                       %s\n", batchmode ? "Batch" : "Simple");
1341         if (enabled) {
1342                 ast_cli(a->fd, "  Log unanswered calls:       %s\n\n", unanswered ? "Yes" : "No");
1343                 if (batchmode) {
1344                         ast_cli(a->fd, "* Batch Mode Settings\n");
1345                         ast_cli(a->fd, "  -------------------\n");
1346                         if (batch)
1347                                 cnt = batch->size;
1348                         if (cdr_sched > -1)
1349                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
1350                         ast_cli(a->fd, "  Safe shutdown:              %s\n", batchsafeshutdown ? "Enabled" : "Disabled");
1351                         ast_cli(a->fd, "  Threading model:            %s\n", batchscheduleronly ? "Scheduler only" : "Scheduler plus separate threads");
1352                         ast_cli(a->fd, "  Current batch size:         %d record%s\n", cnt, ESS(cnt));
1353                         ast_cli(a->fd, "  Maximum batch size:         %d record%s\n", batchsize, ESS(batchsize));
1354                         ast_cli(a->fd, "  Maximum batch time:         %d second%s\n", batchtime, ESS(batchtime));
1355                         ast_cli(a->fd, "  Next batch processing time: %ld second%s\n\n", nextbatchtime, ESS(nextbatchtime));
1356                 }
1357                 ast_cli(a->fd, "* Registered Backends\n");
1358                 ast_cli(a->fd, "  -------------------\n");
1359                 AST_RWLIST_RDLOCK(&be_list);
1360                 if (AST_RWLIST_EMPTY(&be_list)) {
1361                         ast_cli(a->fd, "    (none)\n");
1362                 } else {
1363                         AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
1364                                 ast_cli(a->fd, "    %s\n", beitem->name);
1365                         }
1366                 }
1367                 AST_RWLIST_UNLOCK(&be_list);
1368                 ast_cli(a->fd, "\n");
1369         }
1370
1371         return CLI_SUCCESS;
1372 }
1373
1374 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1375 {
1376         switch (cmd) {
1377         case CLI_INIT:
1378                 e->command = "cdr submit";
1379                 e->usage = 
1380                         "Usage: cdr submit\n"
1381                         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n";
1382                 return NULL;
1383         case CLI_GENERATE:
1384                 return NULL;
1385         }
1386         if (a->argc > 2)
1387                 return CLI_SHOWUSAGE;
1388
1389         submit_unscheduled_batch();
1390         ast_cli(a->fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1391
1392         return CLI_SUCCESS;
1393 }
1394
1395 static struct ast_cli_entry cli_submit = AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data");
1396 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CDR status");
1397
1398 static int do_reload(int reload)
1399 {
1400         struct ast_config *config;
1401         const char *enabled_value;
1402         const char *unanswered_value;
1403         const char *batched_value;
1404         const char *scheduleronly_value;
1405         const char *batchsafeshutdown_value;
1406         const char *size_value;
1407         const char *time_value;
1408         const char *end_before_h_value;
1409         const char *initiatedseconds_value;
1410         int cfg_size;
1411         int cfg_time;
1412         int was_enabled;
1413         int was_batchmode;
1414         int res=0;
1415         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1416
1417         if ((config = ast_config_load2("cdr.conf", "cdr", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
1418                 return 0;
1419         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEUNCHANGED || config == CONFIG_STATUS_FILEINVALID) {
1420                 return 0;
1421         }
1422
1423         ast_mutex_lock(&cdr_batch_lock);
1424
1425         batchsize = BATCH_SIZE_DEFAULT;
1426         batchtime = BATCH_TIME_DEFAULT;
1427         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1428         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1429         was_enabled = enabled;
1430         was_batchmode = batchmode;
1431         enabled = 1;
1432         batchmode = 0;
1433
1434         /* don't run the next scheduled CDR posting while reloading */
1435         AST_SCHED_DEL(sched, cdr_sched);
1436
1437         if (config) {
1438                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1439                         enabled = ast_true(enabled_value);
1440                 }
1441                 if ((unanswered_value = ast_variable_retrieve(config, "general", "unanswered"))) {
1442                         unanswered = ast_true(unanswered_value);
1443                 }
1444                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1445                         batchmode = ast_true(batched_value);
1446                 }
1447                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1448                         batchscheduleronly = ast_true(scheduleronly_value);
1449                 }
1450                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1451                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1452                 }
1453                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1454                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1455                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1456                         else if (cfg_size < 0)
1457                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1458                         else
1459                                 batchsize = cfg_size;
1460                 }
1461                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1462                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1463                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1464                         else if (cfg_time < 0)
1465                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1466                         else
1467                                 batchtime = cfg_time;
1468                 }
1469                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1470                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN);
1471                 if ((initiatedseconds_value = ast_variable_retrieve(config, "general", "initiatedseconds")))
1472                         ast_set2_flag(&ast_options, ast_true(initiatedseconds_value), AST_OPT_FLAG_INITIATED_SECONDS);
1473         }
1474
1475         if (enabled && !batchmode) {
1476                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1477         } else if (enabled && batchmode) {
1478                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1479                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1480         } else {
1481                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1482         }
1483
1484         /* if this reload enabled the CDR batch mode, create the background thread
1485            if it does not exist */
1486         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1487                 ast_cond_init(&cdr_pending_cond, NULL);
1488                 if (ast_pthread_create_background(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1489                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1490                         AST_SCHED_DEL(sched, cdr_sched);
1491                 } else {
1492                         ast_cli_register(&cli_submit);
1493                         ast_register_atexit(ast_cdr_engine_term);
1494                         res = 0;
1495                 }
1496         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1497            kill it */
1498         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1499                 /* wake up the thread so it will exit */
1500                 pthread_cancel(cdr_thread);
1501                 pthread_kill(cdr_thread, SIGURG);
1502                 pthread_join(cdr_thread, NULL);
1503                 cdr_thread = AST_PTHREADT_NULL;
1504                 ast_cond_destroy(&cdr_pending_cond);
1505                 ast_cli_unregister(&cli_submit);
1506                 ast_unregister_atexit(ast_cdr_engine_term);
1507                 res = 0;
1508                 /* if leaving batch mode, then post the CDRs in the batch,
1509                    and don't reschedule, since we are stopping CDR logging */
1510                 if (!batchmode && was_batchmode) {
1511                         ast_cdr_engine_term();
1512                 }
1513         } else {
1514                 res = 0;
1515         }
1516
1517         ast_mutex_unlock(&cdr_batch_lock);
1518         ast_config_destroy(config);
1519         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: CDR\r\nMessage: CDR subsystem reload requested\r\n");
1520
1521         return res;
1522 }
1523
1524 int ast_cdr_engine_init(void)
1525 {
1526         int res;
1527
1528         sched = sched_context_create();
1529         if (!sched) {
1530                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1531                 return -1;
1532         }
1533
1534         ast_cli_register(&cli_status);
1535
1536         res = do_reload(0);
1537         if (res) {
1538                 ast_mutex_lock(&cdr_batch_lock);
1539                 res = init_batch();
1540                 ast_mutex_unlock(&cdr_batch_lock);
1541         }
1542
1543         return res;
1544 }
1545
1546 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1547    hanging up channels, and then again, after the channel hangup timeout expires */
1548 void ast_cdr_engine_term(void)
1549 {
1550         ast_cdr_submit_batch(batchsafeshutdown);
1551 }
1552
1553 int ast_cdr_engine_reload(void)
1554 {
1555         return do_reload(1);
1556 }
1557