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