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