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