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