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