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