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