Merged revisions 316265 via svnmerge from
[asterisk/asterisk.git] / main / cdr.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Call Detail Record API
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \note Includes code and algorithms from the Zapata library.
26  *
27  * \note We do a lot of checking here in the CDR code to try to be sure we don't ever let a CDR slip
28  * through our fingers somehow.  If someone allocates a CDR, it must be completely handled normally
29  * or a WARNING shall be logged, so that we can best keep track of any escape condition where the CDR
30  * isn't properly generated and posted.
31  */
32
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <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 #include "asterisk/data.h"
53
54 /*! Default AMA flag for billing records (CDR's) */
55 int ast_default_amaflags = AST_CDR_DOCUMENTATION;
56 char ast_default_accountcode[AST_MAX_ACCOUNT_CODE];
57
58 struct ast_cdr_beitem {
59         char name[20];
60         char desc[80];
61         ast_cdrbe be;
62         AST_RWLIST_ENTRY(ast_cdr_beitem) list;
63 };
64
65 static AST_RWLIST_HEAD_STATIC(be_list, ast_cdr_beitem);
66
67 struct ast_cdr_batch_item {
68         struct ast_cdr *cdr;
69         struct ast_cdr_batch_item *next;
70 };
71
72 static struct ast_cdr_batch {
73         int size;
74         struct ast_cdr_batch_item *head;
75         struct ast_cdr_batch_item *tail;
76 } *batch = NULL;
77
78
79 static int cdr_sequence =  0;
80
81 static int cdr_seq_inc(struct ast_cdr *cdr);
82
83 static struct ast_sched_context *sched;
84 static int cdr_sched = -1;
85 static pthread_t cdr_thread = AST_PTHREADT_NULL;
86
87 static int enabled;
88 static const int ENABLED_DEFAULT = 1;
89
90 static int batchmode;
91 static const int BATCHMODE_DEFAULT = 0;
92
93 static int unanswered;
94 static const int UNANSWERED_DEFAULT = 0;
95
96 static int batchsize;
97 static const int BATCH_SIZE_DEFAULT = 100;
98
99 static int batchtime;
100 static const int BATCH_TIME_DEFAULT = 300;
101
102 static int batchscheduleronly;
103 static const int BATCH_SCHEDULER_ONLY_DEFAULT = 0;
104
105 static int batchsafeshutdown;
106 static const int BATCH_SAFE_SHUTDOWN_DEFAULT = 1;
107
108 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
109
110 /* these are used to wake up the CDR thread when there's work to do */
111 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
112 static ast_cond_t cdr_pending_cond;
113
114 int check_cdr_enabled()
115 {
116         return enabled;
117 }
118
119 /*! Register a CDR driver. Each registered CDR driver generates a CDR
120         \return 0 on success, -1 on failure
121 */
122 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
123 {
124         struct ast_cdr_beitem *i = NULL;
125
126         if (!name)
127                 return -1;
128
129         if (!be) {
130                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
131                 return -1;
132         }
133
134         AST_RWLIST_WRLOCK(&be_list);
135         AST_RWLIST_TRAVERSE(&be_list, i, list) {
136                 if (!strcasecmp(name, i->name)) {
137                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
138                         AST_RWLIST_UNLOCK(&be_list);
139                         return -1;
140                 }
141         }
142
143         if (!(i = ast_calloc(1, sizeof(*i))))
144                 return -1;
145
146         i->be = be;
147         ast_copy_string(i->name, name, sizeof(i->name));
148         ast_copy_string(i->desc, desc, sizeof(i->desc));
149
150         AST_RWLIST_INSERT_HEAD(&be_list, i, list);
151         AST_RWLIST_UNLOCK(&be_list);
152
153         return 0;
154 }
155
156 /*! unregister a CDR driver */
157 void ast_cdr_unregister(const char *name)
158 {
159         struct ast_cdr_beitem *i = NULL;
160
161         AST_RWLIST_WRLOCK(&be_list);
162         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&be_list, i, list) {
163                 if (!strcasecmp(name, i->name)) {
164                         AST_RWLIST_REMOVE_CURRENT(list);
165                         break;
166                 }
167         }
168         AST_RWLIST_TRAVERSE_SAFE_END;
169         AST_RWLIST_UNLOCK(&be_list);
170
171         if (i) {
172                 ast_verb(2, "Unregistered '%s' CDR backend\n", name);
173                 ast_free(i);
174         }
175 }
176
177 int ast_cdr_isset_unanswered(void)
178 {
179         return unanswered;
180 }
181
182 struct ast_cdr *ast_cdr_dup_unique(struct ast_cdr *cdr)
183 {
184         struct ast_cdr *newcdr = ast_cdr_dup(cdr);
185         if (!newcdr)
186                 return NULL;
187
188         cdr_seq_inc(newcdr);
189         return newcdr;
190 }
191
192 struct ast_cdr *ast_cdr_dup_unique_swap(struct ast_cdr *cdr)
193 {
194         struct ast_cdr *newcdr = ast_cdr_dup(cdr);
195         if (!newcdr)
196                 return NULL;
197
198         cdr_seq_inc(cdr);
199         return newcdr;
200 }
201
202 /*! Duplicate a CDR record
203         \returns Pointer to new CDR record
204 */
205 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
206 {
207         struct ast_cdr *newcdr;
208
209         if (!cdr) /* don't die if we get a null cdr pointer */
210                 return NULL;
211         newcdr = ast_cdr_alloc();
212         if (!newcdr)
213                 return NULL;
214
215         memcpy(newcdr, cdr, sizeof(*newcdr));
216         /* The varshead is unusable, volatile even, after the memcpy so we take care of that here */
217         memset(&newcdr->varshead, 0, sizeof(newcdr->varshead));
218         ast_cdr_copy_vars(newcdr, cdr);
219         newcdr->next = NULL;
220
221         return newcdr;
222 }
223
224 static const char *ast_cdr_getvar_internal(struct ast_cdr *cdr, const char *name, int recur)
225 {
226         if (ast_strlen_zero(name))
227                 return NULL;
228
229         for (; cdr; cdr = recur ? cdr->next : NULL) {
230                 struct ast_var_t *variables;
231                 struct varshead *headp = &cdr->varshead;
232                 AST_LIST_TRAVERSE(headp, variables, entries) {
233                         if (!strcasecmp(name, ast_var_name(variables)))
234                                 return ast_var_value(variables);
235                 }
236         }
237
238         return NULL;
239 }
240
241 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
242 {
243         if (fmt == NULL) {      /* raw mode */
244                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
245         } else {
246                 if (when.tv_sec) {
247                         struct ast_tm tm;
248
249                         ast_localtime(&when, &tm, NULL);
250                         ast_strftime(buf, bufsize, fmt, &tm);
251                 }
252         }
253 }
254
255 /*! CDR channel variable retrieval */
256 void ast_cdr_getvar(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int recur, int raw)
257 {
258         const char *fmt = "%Y-%m-%d %T";
259         const char *varbuf;
260
261         if (!cdr)  /* don't die if the cdr is null */
262                 return;
263
264         *ret = NULL;
265         /* special vars (the ones from the struct ast_cdr when requested by name)
266            I'd almost say we should convert all the stringed vals to vars */
267
268         if (!strcasecmp(name, "clid"))
269                 ast_copy_string(workspace, cdr->clid, workspacelen);
270         else if (!strcasecmp(name, "src"))
271                 ast_copy_string(workspace, cdr->src, workspacelen);
272         else if (!strcasecmp(name, "dst"))
273                 ast_copy_string(workspace, cdr->dst, workspacelen);
274         else if (!strcasecmp(name, "dcontext"))
275                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
276         else if (!strcasecmp(name, "channel"))
277                 ast_copy_string(workspace, cdr->channel, workspacelen);
278         else if (!strcasecmp(name, "dstchannel"))
279                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
280         else if (!strcasecmp(name, "lastapp"))
281                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
282         else if (!strcasecmp(name, "lastdata"))
283                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
284         else if (!strcasecmp(name, "start"))
285                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
286         else if (!strcasecmp(name, "answer"))
287                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
288         else if (!strcasecmp(name, "end"))
289                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
290         else if (!strcasecmp(name, "duration"))
291                 snprintf(workspace, workspacelen, "%ld", cdr->duration ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
292         else if (!strcasecmp(name, "billsec"))
293                 snprintf(workspace, workspacelen, "%ld", cdr->billsec || cdr->answer.tv_sec == 0 ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
294         else if (!strcasecmp(name, "disposition")) {
295                 if (raw) {
296                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
297                 } else {
298                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
299                 }
300         } else if (!strcasecmp(name, "amaflags")) {
301                 if (raw) {
302                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
303                 } else {
304                         ast_copy_string(workspace, ast_cdr_flags2str(cdr->amaflags), workspacelen);
305                 }
306         } else if (!strcasecmp(name, "accountcode"))
307                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
308         else if (!strcasecmp(name, "peeraccount"))
309                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
310         else if (!strcasecmp(name, "uniqueid"))
311                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
312         else if (!strcasecmp(name, "linkedid"))
313                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
314         else if (!strcasecmp(name, "userfield"))
315                 ast_copy_string(workspace, cdr->userfield, workspacelen);
316         else if (!strcasecmp(name, "sequence"))
317                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
318         else if ((varbuf = ast_cdr_getvar_internal(cdr, name, recur)))
319                 ast_copy_string(workspace, varbuf, workspacelen);
320         else
321                 workspace[0] = '\0';
322
323         if (!ast_strlen_zero(workspace))
324                 *ret = workspace;
325 }
326
327 /* readonly cdr variables */
328 static const char * const cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
329                                                   "lastapp", "lastdata", "start", "answer", "end", "duration",
330                                                   "billsec", "disposition", "amaflags", "accountcode", "uniqueid", "linkedid",
331                                                   "userfield", "sequence", NULL };
332 /*! Set a CDR channel variable
333         \note You can't set the CDR variables that belong to the actual CDR record, like "billsec".
334 */
335 int ast_cdr_setvar(struct ast_cdr *cdr, const char *name, const char *value, int recur)
336 {
337         struct ast_var_t *newvariable;
338         struct varshead *headp;
339         int x;
340
341         for (x = 0; cdr_readonly_vars[x]; x++) {
342                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
343                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!.\n", name);
344                         return -1;
345                 }
346         }
347
348         if (!cdr) {
349                 ast_log(LOG_ERROR, "Attempt to set a variable on a nonexistent CDR record.\n");
350                 return -1;
351         }
352
353         for (; cdr; cdr = recur ? cdr->next : NULL) {
354                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
355                         continue;
356                 headp = &cdr->varshead;
357                 AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
358                         if (!strcasecmp(ast_var_name(newvariable), name)) {
359                                 /* there is already such a variable, delete it */
360                                 AST_LIST_REMOVE_CURRENT(entries);
361                                 ast_var_delete(newvariable);
362                                 break;
363                         }
364                 }
365                 AST_LIST_TRAVERSE_SAFE_END;
366
367                 if (value) {
368                         newvariable = ast_var_assign(name, value);
369                         AST_LIST_INSERT_HEAD(headp, newvariable, entries);
370                 }
371         }
372
373         return 0;
374 }
375
376 int ast_cdr_copy_vars(struct ast_cdr *to_cdr, struct ast_cdr *from_cdr)
377 {
378         struct ast_var_t *variables, *newvariable = NULL;
379         struct varshead *headpa, *headpb;
380         const char *var, *val;
381         int x = 0;
382
383         if (!to_cdr || !from_cdr) /* don't die if one of the pointers is null */
384                 return 0;
385
386         headpa = &from_cdr->varshead;
387         headpb = &to_cdr->varshead;
388
389         AST_LIST_TRAVERSE(headpa,variables,entries) {
390                 if (variables &&
391                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
392                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
393                         newvariable = ast_var_assign(var, val);
394                         AST_LIST_INSERT_HEAD(headpb, newvariable, entries);
395                         x++;
396                 }
397         }
398
399         return x;
400 }
401
402 int ast_cdr_serialize_variables(struct ast_cdr *cdr, struct ast_str **buf, char delim, char sep, int recur)
403 {
404         struct ast_var_t *variables;
405         const char *var;
406         char *tmp;
407         char workspace[256];
408         int total = 0, x = 0, i;
409
410         ast_str_reset(*buf);
411
412         for (; cdr; cdr = recur ? cdr->next : NULL) {
413                 if (++x > 1)
414                         ast_str_append(buf, 0, "\n");
415
416                 AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
417                         if (!(var = ast_var_name(variables))) {
418                                 continue;
419                         }
420
421                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variables), ""), sep) < 0) {
422                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
423                                 break;
424                         }
425
426                         total++;
427                 }
428
429                 for (i = 0; cdr_readonly_vars[i]; i++) {
430                         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 */
431                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
432                         if (!tmp)
433                                 continue;
434
435                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep) < 0) {
436                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
437                                 break;
438                         } else
439                                 total++;
440                 }
441         }
442
443         return total;
444 }
445
446
447 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
448 {
449
450         /* clear variables */
451         for (; cdr; cdr = recur ? cdr->next : NULL) {
452                 struct ast_var_t *vardata;
453                 struct varshead *headp = &cdr->varshead;
454                 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
455                         ast_var_delete(vardata);
456         }
457 }
458
459 /*! \brief  print a warning if cdr already posted */
460 static void check_post(struct ast_cdr *cdr)
461 {
462         if (!cdr)
463                 return;
464         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
465                 ast_log(LOG_NOTICE, "CDR on channel '%s' already posted\n", S_OR(cdr->channel, "<unknown>"));
466 }
467
468 void ast_cdr_free(struct ast_cdr *cdr)
469 {
470
471         while (cdr) {
472                 struct ast_cdr *next = cdr->next;
473
474                 ast_cdr_free_vars(cdr, 0);
475                 ast_free(cdr);
476                 cdr = next;
477         }
478 }
479
480 /*! \brief the same as a cdr_free call, only with no checks; just get rid of it */
481 void ast_cdr_discard(struct ast_cdr *cdr)
482 {
483         while (cdr) {
484                 struct ast_cdr *next = cdr->next;
485
486                 ast_cdr_free_vars(cdr, 0);
487                 ast_free(cdr);
488                 cdr = next;
489         }
490 }
491
492 struct ast_cdr *ast_cdr_alloc(void)
493 {
494         struct ast_cdr *x;
495         x = ast_calloc(1, sizeof(*x));
496         if (!x)
497                 ast_log(LOG_ERROR,"Allocation Failure for a CDR!\n");
498         return x;
499 }
500
501 static void cdr_merge_vars(struct ast_cdr *to, struct ast_cdr *from)
502 {
503         struct ast_var_t *variablesfrom,*variablesto;
504         struct varshead *headpfrom = &to->varshead;
505         struct varshead *headpto = &from->varshead;
506         AST_LIST_TRAVERSE_SAFE_BEGIN(headpfrom, variablesfrom, entries) {
507                 /* for every var in from, stick it in to */
508                 const char *fromvarname, *fromvarval;
509                 const char *tovarname = NULL, *tovarval = NULL;
510                 fromvarname = ast_var_name(variablesfrom);
511                 fromvarval = ast_var_value(variablesfrom);
512                 tovarname = 0;
513
514                 /* now, quick see if that var is in the 'to' cdr already */
515                 AST_LIST_TRAVERSE(headpto, variablesto, entries) {
516
517                         /* now, quick see if that var is in the 'to' cdr already */
518                         if ( strcasecmp(fromvarname, ast_var_name(variablesto)) == 0 ) {
519                                 tovarname = ast_var_name(variablesto);
520                                 tovarval = ast_var_value(variablesto);
521                                 break;
522                         }
523                 }
524                 if (tovarname && strcasecmp(fromvarval,tovarval) != 0) {  /* this message here to see how irritating the userbase finds it */
525                         ast_log(LOG_NOTICE, "Merging CDR's: variable %s value %s dropped in favor of value %s\n", tovarname, fromvarval, tovarval);
526                         continue;
527                 } else if (tovarname && strcasecmp(fromvarval,tovarval) == 0) /* if they are the same, the job is done */
528                         continue;
529
530                 /* rip this var out of the from cdr, and stick it in the to cdr */
531                 AST_LIST_MOVE_CURRENT(headpto, entries);
532         }
533         AST_LIST_TRAVERSE_SAFE_END;
534 }
535
536 void ast_cdr_merge(struct ast_cdr *to, struct ast_cdr *from)
537 {
538         struct ast_cdr *zcdr;
539         struct ast_cdr *lto = NULL;
540         struct ast_cdr *lfrom = NULL;
541         int discard_from = 0;
542
543         if (!to || !from)
544                 return;
545
546         /* don't merge into locked CDR's -- it's bad business */
547         if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
548                 zcdr = to; /* safety valve? */
549                 while (to->next) {
550                         lto = to;
551                         to = to->next;
552                 }
553
554                 if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
555                         ast_log(LOG_WARNING, "Merging into locked CDR... no choice.");
556                         to = zcdr; /* safety-- if all there are is locked CDR's, then.... ?? */
557                         lto = NULL;
558                 }
559         }
560
561         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED)) {
562                 struct ast_cdr *llfrom = NULL;
563                 discard_from = 1;
564                 if (lto) {
565                         /* insert the from stuff after lto */
566                         lto->next = from;
567                         lfrom = from;
568                         while (lfrom && lfrom->next) {
569                                 if (!lfrom->next->next)
570                                         llfrom = lfrom;
571                                 lfrom = lfrom->next;
572                         }
573                         /* rip off the last entry and put a copy of the to at the end */
574                         llfrom->next = to;
575                         from = lfrom;
576                 } else {
577                         /* save copy of the current *to cdr */
578                         struct ast_cdr tcdr;
579                         memcpy(&tcdr, to, sizeof(tcdr));
580                         /* copy in the locked from cdr */
581                         memcpy(to, from, sizeof(*to));
582                         lfrom = from;
583                         while (lfrom && lfrom->next) {
584                                 if (!lfrom->next->next)
585                                         llfrom = lfrom;
586                                 lfrom = lfrom->next;
587                         }
588                         from->next = NULL;
589                         /* rip off the last entry and put a copy of the to at the end */
590                         if (llfrom == from)
591                                 to = to->next = ast_cdr_dup(&tcdr);
592                         else
593                                 to = llfrom->next = ast_cdr_dup(&tcdr);
594                         from = lfrom;
595                 }
596         }
597
598         if (!ast_tvzero(from->start)) {
599                 if (!ast_tvzero(to->start)) {
600                         if (ast_tvcmp(to->start, from->start) > 0 ) {
601                                 to->start = from->start; /* use the earliest time */
602                                 from->start = ast_tv(0,0); /* we actively "steal" these values */
603                         }
604                         /* else nothing to do */
605                 } else {
606                         to->start = from->start;
607                         from->start = ast_tv(0,0); /* we actively "steal" these values */
608                 }
609         }
610         if (!ast_tvzero(from->answer)) {
611                 if (!ast_tvzero(to->answer)) {
612                         if (ast_tvcmp(to->answer, from->answer) > 0 ) {
613                                 to->answer = from->answer; /* use the earliest time */
614                                 from->answer = ast_tv(0,0); /* we actively "steal" these values */
615                         }
616                         /* we got the earliest answer time, so we'll settle for that? */
617                 } else {
618                         to->answer = from->answer;
619                         from->answer = ast_tv(0,0); /* we actively "steal" these values */
620                 }
621         }
622         if (!ast_tvzero(from->end)) {
623                 if (!ast_tvzero(to->end)) {
624                         if (ast_tvcmp(to->end, from->end) < 0 ) {
625                                 to->end = from->end; /* use the latest time */
626                                 from->end = ast_tv(0,0); /* we actively "steal" these values */
627                                 to->duration = to->end.tv_sec - to->start.tv_sec;  /* don't forget to update the duration, billsec, when we set end */
628                                 to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
629                         }
630                         /* else, nothing to do */
631                 } else {
632                         to->end = from->end;
633                         from->end = ast_tv(0,0); /* we actively "steal" these values */
634                         to->duration = to->end.tv_sec - to->start.tv_sec;
635                         to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
636                 }
637         }
638         if (to->disposition < from->disposition) {
639                 to->disposition = from->disposition;
640                 from->disposition = AST_CDR_NOANSWER;
641         }
642         if (ast_strlen_zero(to->lastapp) && !ast_strlen_zero(from->lastapp)) {
643                 ast_copy_string(to->lastapp, from->lastapp, sizeof(to->lastapp));
644                 from->lastapp[0] = 0; /* theft */
645         }
646         if (ast_strlen_zero(to->lastdata) && !ast_strlen_zero(from->lastdata)) {
647                 ast_copy_string(to->lastdata, from->lastdata, sizeof(to->lastdata));
648                 from->lastdata[0] = 0; /* theft */
649         }
650         if (ast_strlen_zero(to->dcontext) && !ast_strlen_zero(from->dcontext)) {
651                 ast_copy_string(to->dcontext, from->dcontext, sizeof(to->dcontext));
652                 from->dcontext[0] = 0; /* theft */
653         }
654         if (ast_strlen_zero(to->dstchannel) && !ast_strlen_zero(from->dstchannel)) {
655                 ast_copy_string(to->dstchannel, from->dstchannel, sizeof(to->dstchannel));
656                 from->dstchannel[0] = 0; /* theft */
657         }
658         if (!ast_strlen_zero(from->channel) && (ast_strlen_zero(to->channel) || !strncasecmp(from->channel, "Agent/", 6))) {
659                 ast_copy_string(to->channel, from->channel, sizeof(to->channel));
660                 from->channel[0] = 0; /* theft */
661         }
662         if (ast_strlen_zero(to->src) && !ast_strlen_zero(from->src)) {
663                 ast_copy_string(to->src, from->src, sizeof(to->src));
664                 from->src[0] = 0; /* theft */
665         }
666         if (ast_strlen_zero(to->clid) && !ast_strlen_zero(from->clid)) {
667                 ast_copy_string(to->clid, from->clid, sizeof(to->clid));
668                 from->clid[0] = 0; /* theft */
669         }
670         if (ast_strlen_zero(to->dst) && !ast_strlen_zero(from->dst)) {
671                 ast_copy_string(to->dst, from->dst, sizeof(to->dst));
672                 from->dst[0] = 0; /* theft */
673         }
674         if (!to->amaflags)
675                 to->amaflags = AST_CDR_DOCUMENTATION;
676         if (!from->amaflags)
677                 from->amaflags = AST_CDR_DOCUMENTATION; /* make sure both amaflags are set to something (DOC is default) */
678         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (to->amaflags == AST_CDR_DOCUMENTATION && from->amaflags != AST_CDR_DOCUMENTATION)) {
679                 to->amaflags = from->amaflags;
680         }
681         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->accountcode) && !ast_strlen_zero(from->accountcode))) {
682                 ast_copy_string(to->accountcode, from->accountcode, sizeof(to->accountcode));
683         }
684         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->peeraccount) && !ast_strlen_zero(from->peeraccount))) {
685                 ast_copy_string(to->peeraccount, from->peeraccount, sizeof(to->peeraccount));
686         }
687         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->userfield) && !ast_strlen_zero(from->userfield))) {
688                 ast_copy_string(to->userfield, from->userfield, sizeof(to->userfield));
689         }
690         /* flags, varsead, ? */
691         cdr_merge_vars(from, to);
692
693         if (ast_test_flag(from, AST_CDR_FLAG_KEEP_VARS))
694                 ast_set_flag(to, AST_CDR_FLAG_KEEP_VARS);
695         if (ast_test_flag(from, AST_CDR_FLAG_POSTED))
696                 ast_set_flag(to, AST_CDR_FLAG_POSTED);
697         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED))
698                 ast_set_flag(to, AST_CDR_FLAG_LOCKED);
699         if (ast_test_flag(from, AST_CDR_FLAG_CHILD))
700                 ast_set_flag(to, AST_CDR_FLAG_CHILD);
701         if (ast_test_flag(from, AST_CDR_FLAG_POST_DISABLED))
702                 ast_set_flag(to, AST_CDR_FLAG_POST_DISABLED);
703
704         /* last, but not least, we need to merge any forked CDRs to the 'to' cdr */
705         while (from->next) {
706                 /* just rip 'em off the 'from' and insert them on the 'to' */
707                 zcdr = from->next;
708                 from->next = zcdr->next;
709                 zcdr->next = NULL;
710                 /* zcdr is now ripped from the current list; */
711                 ast_cdr_append(to, zcdr);
712         }
713         if (discard_from)
714                 ast_cdr_discard(from);
715 }
716
717 void ast_cdr_start(struct ast_cdr *cdr)
718 {
719         for (; cdr; cdr = cdr->next) {
720                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
721                         check_post(cdr);
722                         cdr->start = ast_tvnow();
723                 }
724         }
725 }
726
727 void ast_cdr_answer(struct ast_cdr *cdr)
728 {
729
730         for (; cdr; cdr = cdr->next) {
731                 if (ast_test_flag(cdr, AST_CDR_FLAG_ANSLOCKED))
732                         continue;
733                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
734                         continue;
735                 check_post(cdr);
736                 if (cdr->disposition < AST_CDR_ANSWERED)
737                         cdr->disposition = AST_CDR_ANSWERED;
738                 if (ast_tvzero(cdr->answer))
739                         cdr->answer = ast_tvnow();
740         }
741 }
742
743 void ast_cdr_busy(struct ast_cdr *cdr)
744 {
745
746         for (; cdr; cdr = cdr->next) {
747                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
748                         check_post(cdr);
749                         cdr->disposition = AST_CDR_BUSY;
750                 }
751         }
752 }
753
754 void ast_cdr_failed(struct ast_cdr *cdr)
755 {
756         for (; cdr; cdr = cdr->next) {
757                 check_post(cdr);
758                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
759                         check_post(cdr);
760                         if (cdr->disposition < AST_CDR_FAILED)
761                                 cdr->disposition = AST_CDR_FAILED;
762                 }
763         }
764 }
765
766 void ast_cdr_noanswer(struct ast_cdr *cdr)
767 {
768         while (cdr) {
769                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
770                         check_post(cdr);
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         const char *num;
852
853         if (!cdr) {
854                 return;
855         }
856
857         /* Grab source from ANI or normal Caller*ID */
858         num = S_COR(c->caller.ani.number.valid, c->caller.ani.number.str,
859                 S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL));
860         ast_callerid_merge(cdr->clid, sizeof(cdr->clid),
861                 S_COR(c->caller.id.name.valid, c->caller.id.name.str, NULL), num, "");
862         ast_copy_string(cdr->src, S_OR(num, ""), sizeof(cdr->src));
863         ast_cdr_setvar(cdr, "dnid", S_OR(c->dialed.number.str, ""), 0);
864
865         if (c->caller.id.subaddress.valid) {
866                 ast_cdr_setvar(cdr, "callingsubaddr", S_OR(c->caller.id.subaddress.str, ""), 0);
867         }
868         if (c->dialed.subaddress.valid) {
869                 ast_cdr_setvar(cdr, "calledsubaddr", S_OR(c->dialed.subaddress.str, ""), 0);
870         }
871 }
872
873 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
874 {
875         for (; cdr; cdr = cdr->next) {
876                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
877                         set_one_cid(cdr, c);
878         }
879         return 0;
880 }
881
882 static int cdr_seq_inc(struct ast_cdr *cdr)
883 {
884         return (cdr->sequence = ast_atomic_fetchadd_int(&cdr_sequence, +1));
885 }
886
887 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
888 {
889         for ( ; cdr ; cdr = cdr->next) {
890                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
891                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
892                         set_one_cid(cdr, c);
893                         cdr_seq_inc(cdr);
894
895                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NOANSWER;
896                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
897                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
898                         ast_copy_string(cdr->peeraccount, c->peeraccount, sizeof(cdr->peeraccount));
899                         /* Destination information */
900                         ast_copy_string(cdr->dst, S_OR(c->macroexten,c->exten), sizeof(cdr->dst));
901                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext,c->context), sizeof(cdr->dcontext));
902                         /* Unique call identifier */
903                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
904                         /* Linked call identifier */
905                         ast_copy_string(cdr->linkedid, c->linkedid, sizeof(cdr->linkedid));
906                 }
907         }
908         return 0;
909 }
910
911 /* Three routines were "fixed" via 10668, and later shown that
912    users were depending on this behavior. ast_cdr_end,
913    ast_cdr_setvar and ast_cdr_answer are the three routines.
914    While most of the other routines would not touch
915    LOCKED cdr's, these three routines were designed to
916    operate on locked CDR's as a matter of course.
917    I now appreciate how this plays with the ForkCDR app,
918    which forms these cdr chains in the first place.
919    cdr_end is pretty key: all cdrs created are closed
920    together. They only vary by start time. Arithmetically,
921    users can calculate the subintervals they wish to track. */
922
923 void ast_cdr_end(struct ast_cdr *cdr)
924 {
925         for ( ; cdr ; cdr = cdr->next) {
926                 if (ast_test_flag(cdr, AST_CDR_FLAG_DONT_TOUCH) && ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
927                         continue;
928                 check_post(cdr);
929                 if (ast_tvzero(cdr->end))
930                         cdr->end = ast_tvnow();
931                 if (ast_tvzero(cdr->start)) {
932                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", S_OR(cdr->channel, "<unknown>"));
933                         cdr->disposition = AST_CDR_FAILED;
934                 } else
935                         cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
936                 if (ast_tvzero(cdr->answer)) {
937                         if (cdr->disposition == AST_CDR_ANSWERED) {
938                                 ast_log(LOG_WARNING, "CDR on channel '%s' has no answer time but is 'ANSWERED'\n", S_OR(cdr->channel, "<unknown>"));
939                                 cdr->disposition = AST_CDR_FAILED;
940                         }
941                 } else {
942                         cdr->billsec = cdr->end.tv_sec - cdr->answer.tv_sec;
943                         if (ast_test_flag(&ast_options, AST_OPT_FLAG_INITIATED_SECONDS))
944                                 cdr->billsec += cdr->end.tv_usec > cdr->answer.tv_usec ? 1 : 0;
945                 }
946         }
947 }
948
949 char *ast_cdr_disp2str(int disposition)
950 {
951         switch (disposition) {
952         case AST_CDR_NULL:
953                 return "NO ANSWER"; /* by default, for backward compatibility */
954         case AST_CDR_NOANSWER:
955                 return "NO ANSWER";
956         case AST_CDR_FAILED:
957                 return "FAILED";
958         case AST_CDR_BUSY:
959                 return "BUSY";
960         case AST_CDR_ANSWERED:
961                 return "ANSWERED";
962         }
963         return "UNKNOWN";
964 }
965
966 /*! Converts AMA flag to printable string */
967 char *ast_cdr_flags2str(int flag)
968 {
969         switch (flag) {
970         case AST_CDR_OMIT:
971                 return "OMIT";
972         case AST_CDR_BILLING:
973                 return "BILLING";
974         case AST_CDR_DOCUMENTATION:
975                 return "DOCUMENTATION";
976         }
977         return "Unknown";
978 }
979
980 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
981 {
982         struct ast_cdr *cdr = chan->cdr;
983         const char *old_acct = "";
984
985         if (!ast_strlen_zero(chan->accountcode)) {
986                 old_acct = ast_strdupa(chan->accountcode);
987         }
988
989         ast_string_field_set(chan, accountcode, account);
990         for ( ; cdr ; cdr = cdr->next) {
991                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
992                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
993                 }
994         }
995
996         ast_manager_event(chan, EVENT_FLAG_CALL, "NewAccountCode",
997                         "Channel: %s\r\n"
998                         "Uniqueid: %s\r\n"
999                         "AccountCode: %s\r\n"
1000                         "OldAccountCode: %s\r\n",
1001                         chan->name, chan->uniqueid, chan->accountcode, old_acct);
1002
1003         return 0;
1004 }
1005
1006 int ast_cdr_setpeeraccount(struct ast_channel *chan, const char *account)
1007 {
1008         struct ast_cdr *cdr = chan->cdr;
1009         const char *old_acct = "";
1010
1011         if (!ast_strlen_zero(chan->peeraccount)) {
1012                 old_acct = ast_strdupa(chan->peeraccount);
1013         }
1014
1015         ast_string_field_set(chan, peeraccount, account);
1016         for ( ; cdr ; cdr = cdr->next) {
1017                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1018                         ast_copy_string(cdr->peeraccount, chan->peeraccount, sizeof(cdr->peeraccount));
1019                 }
1020         }
1021
1022         ast_manager_event(chan, EVENT_FLAG_CALL, "NewPeerAccount",
1023                         "Channel: %s\r\n"
1024                         "Uniqueid: %s\r\n"
1025                         "PeerAccount: %s\r\n"
1026                         "OldPeerAccount: %s\r\n",
1027                         chan->name, chan->uniqueid, chan->peeraccount, old_acct);
1028
1029         return 0;
1030 }
1031
1032 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
1033 {
1034         struct ast_cdr *cdr;
1035         int newflag = ast_cdr_amaflags2int(flag);
1036         if (newflag) {
1037                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
1038                         if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1039                                 cdr->amaflags = newflag;
1040                         }
1041                 }
1042         }
1043
1044         return 0;
1045 }
1046
1047 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
1048 {
1049         struct ast_cdr *cdr = chan->cdr;
1050
1051         for ( ; cdr ; cdr = cdr->next) {
1052                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
1053                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
1054         }
1055
1056         return 0;
1057 }
1058
1059 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
1060 {
1061         struct ast_cdr *cdr = chan->cdr;
1062
1063         for ( ; cdr ; cdr = cdr->next) {
1064                 int len = strlen(cdr->userfield);
1065
1066                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
1067                         ast_copy_string(cdr->userfield + len, userfield, sizeof(cdr->userfield) - len);
1068         }
1069
1070         return 0;
1071 }
1072
1073 int ast_cdr_update(struct ast_channel *c)
1074 {
1075         struct ast_cdr *cdr = c->cdr;
1076
1077         for ( ; cdr ; cdr = cdr->next) {
1078                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1079                         set_one_cid(cdr, c);
1080
1081                         /* Copy account code et-al */
1082                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
1083                         ast_copy_string(cdr->peeraccount, c->peeraccount, sizeof(cdr->peeraccount));
1084                         ast_copy_string(cdr->linkedid, c->linkedid, sizeof(cdr->linkedid));
1085
1086                         /* Destination information */ /* XXX privilege macro* ? */
1087                         ast_copy_string(cdr->dst, S_OR(c->macroexten, c->exten), sizeof(cdr->dst));
1088                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext, c->context), sizeof(cdr->dcontext));
1089                 }
1090         }
1091
1092         return 0;
1093 }
1094
1095 int ast_cdr_amaflags2int(const char *flag)
1096 {
1097         if (!strcasecmp(flag, "default"))
1098                 return 0;
1099         if (!strcasecmp(flag, "omit"))
1100                 return AST_CDR_OMIT;
1101         if (!strcasecmp(flag, "billing"))
1102                 return AST_CDR_BILLING;
1103         if (!strcasecmp(flag, "documentation"))
1104                 return AST_CDR_DOCUMENTATION;
1105         return -1;
1106 }
1107
1108 static void post_cdr(struct ast_cdr *cdr)
1109 {
1110         struct ast_cdr_beitem *i;
1111
1112         for ( ; cdr ; cdr = cdr->next) {
1113                 if (!unanswered && cdr->disposition < AST_CDR_ANSWERED && (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
1114                         /* For people, who don't want to see unanswered single-channel events */
1115                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1116                         continue;
1117                 }
1118
1119                 /* don't post CDRs that are for dialed channels unless those
1120                  * channels were originated from asterisk (pbx_spool, manager,
1121                  * cli) */
1122                 if (ast_test_flag(cdr, AST_CDR_FLAG_DIALED) && !ast_test_flag(cdr, AST_CDR_FLAG_ORIGINATED)) {
1123                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1124                         continue;
1125                 }
1126
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         }
1495
1496         ast_mutex_lock(&cdr_batch_lock);
1497
1498         was_enabled = enabled;
1499         was_batchmode = batchmode;
1500
1501         batchsize = BATCH_SIZE_DEFAULT;
1502         batchtime = BATCH_TIME_DEFAULT;
1503         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1504         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1505         enabled = ENABLED_DEFAULT;
1506         batchmode = BATCHMODE_DEFAULT;
1507         unanswered = UNANSWERED_DEFAULT;
1508
1509         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1510                 ast_mutex_unlock(&cdr_batch_lock);
1511                 return 0;
1512         }
1513
1514         /* don't run the next scheduled CDR posting while reloading */
1515         AST_SCHED_DEL(sched, cdr_sched);
1516
1517         if (config) {
1518                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1519                         enabled = ast_true(enabled_value);
1520                 }
1521                 if ((unanswered_value = ast_variable_retrieve(config, "general", "unanswered"))) {
1522                         unanswered = ast_true(unanswered_value);
1523                 }
1524                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1525                         batchmode = ast_true(batched_value);
1526                 }
1527                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1528                         batchscheduleronly = ast_true(scheduleronly_value);
1529                 }
1530                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1531                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1532                 }
1533                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1534                         if (sscanf(size_value, "%30d", &cfg_size) < 1)
1535                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1536                         else if (cfg_size < 0)
1537                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1538                         else
1539                                 batchsize = cfg_size;
1540                 }
1541                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1542                         if (sscanf(time_value, "%30d", &cfg_time) < 1)
1543                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1544                         else if (cfg_time < 0)
1545                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1546                         else
1547                                 batchtime = cfg_time;
1548                 }
1549                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1550                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN);
1551                 if ((initiatedseconds_value = ast_variable_retrieve(config, "general", "initiatedseconds")))
1552                         ast_set2_flag(&ast_options, ast_true(initiatedseconds_value), AST_OPT_FLAG_INITIATED_SECONDS);
1553         }
1554
1555         if (enabled && !batchmode) {
1556                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1557         } else if (enabled && batchmode) {
1558                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1559                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1560         } else {
1561                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1562         }
1563
1564         /* if this reload enabled the CDR batch mode, create the background thread
1565            if it does not exist */
1566         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1567                 ast_cond_init(&cdr_pending_cond, NULL);
1568                 if (ast_pthread_create_background(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1569                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1570                         AST_SCHED_DEL(sched, cdr_sched);
1571                 } else {
1572                         ast_cli_register(&cli_submit);
1573                         ast_register_atexit(ast_cdr_engine_term);
1574                         res = 0;
1575                 }
1576         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1577            kill it */
1578         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1579                 /* wake up the thread so it will exit */
1580                 pthread_cancel(cdr_thread);
1581                 pthread_kill(cdr_thread, SIGURG);
1582                 pthread_join(cdr_thread, NULL);
1583                 cdr_thread = AST_PTHREADT_NULL;
1584                 ast_cond_destroy(&cdr_pending_cond);
1585                 ast_cli_unregister(&cli_submit);
1586                 ast_unregister_atexit(ast_cdr_engine_term);
1587                 res = 0;
1588                 /* if leaving batch mode, then post the CDRs in the batch,
1589                    and don't reschedule, since we are stopping CDR logging */
1590                 if (!batchmode && was_batchmode) {
1591                         ast_cdr_engine_term();
1592                 }
1593         } else {
1594                 res = 0;
1595         }
1596
1597         ast_mutex_unlock(&cdr_batch_lock);
1598         ast_config_destroy(config);
1599         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: CDR\r\nMessage: CDR subsystem reload requested\r\n");
1600
1601         return res;
1602 }
1603
1604 int ast_cdr_engine_init(void)
1605 {
1606         int res;
1607
1608         sched = ast_sched_context_create();
1609         if (!sched) {
1610                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1611                 return -1;
1612         }
1613
1614         ast_cli_register(&cli_status);
1615
1616         res = do_reload(0);
1617         if (res) {
1618                 ast_mutex_lock(&cdr_batch_lock);
1619                 res = init_batch();
1620                 ast_mutex_unlock(&cdr_batch_lock);
1621         }
1622
1623         return res;
1624 }
1625
1626 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1627    hanging up channels, and then again, after the channel hangup timeout expires */
1628 void ast_cdr_engine_term(void)
1629 {
1630         ast_cdr_submit_batch(batchsafeshutdown);
1631 }
1632
1633 int ast_cdr_engine_reload(void)
1634 {
1635         return do_reload(1);
1636 }
1637
1638 int ast_cdr_data_add_structure(struct ast_data *tree, struct ast_cdr *cdr, int recur)
1639 {
1640         struct ast_cdr *tmpcdr;
1641         struct ast_data *level;
1642         struct ast_var_t *variables;
1643         const char *var, *val;
1644         int x = 1, i;
1645         char workspace[256];
1646         char *tmp;
1647
1648         if (!cdr) {
1649                 return -1;
1650         }
1651
1652         for (tmpcdr = cdr; tmpcdr; tmpcdr = (recur ? tmpcdr->next : NULL)) {
1653                 level = ast_data_add_node(tree, "level");
1654                 if (!level) {
1655                         continue;
1656                 }
1657
1658                 ast_data_add_int(level, "level_number", x);
1659
1660                 AST_LIST_TRAVERSE(&tmpcdr->varshead, variables, entries) {
1661                         if (variables && (var = ast_var_name(variables)) &&
1662                                         (val = ast_var_value(variables)) && !ast_strlen_zero(var)
1663                                         && !ast_strlen_zero(val)) {
1664                                 ast_data_add_str(level, var, val);
1665                         } else {
1666                                 break;
1667                         }
1668                 }
1669
1670                 for (i = 0; cdr_readonly_vars[i]; i++) {
1671                         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 */
1672                         ast_cdr_getvar(tmpcdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
1673                         if (!tmp) {
1674                                 continue;
1675                         }
1676                         ast_data_add_str(level, cdr_readonly_vars[i], tmp);
1677                 }
1678
1679                 x++;
1680         }
1681
1682         return 0;
1683 }
1684