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