Merged revisions 107016 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 /*! Duplicate a CDR record 
161         \returns Pointer to new CDR record
162 */
163 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr) 
164 {
165         struct ast_cdr *newcdr;
166         
167         if (!cdr) /* don't die if we get a null cdr pointer */
168                 return NULL;
169         newcdr = ast_cdr_alloc();
170         if (!newcdr)
171                 return NULL;
172
173         memcpy(newcdr, cdr, sizeof(*newcdr));
174         /* The varshead is unusable, volatile even, after the memcpy so we take care of that here */
175         memset(&newcdr->varshead, 0, sizeof(newcdr->varshead));
176         ast_cdr_copy_vars(newcdr, cdr);
177         newcdr->next = NULL;
178
179         return newcdr;
180 }
181
182 static const char *ast_cdr_getvar_internal(struct ast_cdr *cdr, const char *name, int recur) 
183 {
184         if (ast_strlen_zero(name))
185                 return NULL;
186
187         for (; cdr; cdr = recur ? cdr->next : NULL) {
188                 struct ast_var_t *variables;
189                 struct varshead *headp = &cdr->varshead;
190                 AST_LIST_TRAVERSE(headp, variables, entries) {
191                         if (!strcasecmp(name, ast_var_name(variables)))
192                                 return ast_var_value(variables);
193                 }
194         }
195
196         return NULL;
197 }
198
199 static void cdr_get_tv(struct timeval tv, const char *fmt, char *buf, int bufsize)
200 {
201         if (fmt == NULL) {      /* raw mode */
202                 snprintf(buf, bufsize, "%ld.%06ld", (long)tv.tv_sec, (long)tv.tv_usec);
203         } else {  
204                 struct ast_tm tm;
205
206                 ast_localtime(&tv, &tm, NULL);
207                 ast_strftime(buf, bufsize, fmt, &tm);
208         }
209 }
210
211 /*! CDR channel variable retrieval */
212 void ast_cdr_getvar(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int recur, int raw) 
213 {
214         const char *fmt = "%Y-%m-%d %T";
215         const char *varbuf;
216
217         if (!cdr)  /* don't die if the cdr is null */
218                 return;
219
220         *ret = NULL;
221         /* special vars (the ones from the struct ast_cdr when requested by name) 
222            I'd almost say we should convert all the stringed vals to vars */
223
224         if (!strcasecmp(name, "clid"))
225                 ast_copy_string(workspace, cdr->clid, workspacelen);
226         else if (!strcasecmp(name, "src"))
227                 ast_copy_string(workspace, cdr->src, workspacelen);
228         else if (!strcasecmp(name, "dst"))
229                 ast_copy_string(workspace, cdr->dst, workspacelen);
230         else if (!strcasecmp(name, "dcontext"))
231                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
232         else if (!strcasecmp(name, "channel"))
233                 ast_copy_string(workspace, cdr->channel, workspacelen);
234         else if (!strcasecmp(name, "dstchannel"))
235                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
236         else if (!strcasecmp(name, "lastapp"))
237                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
238         else if (!strcasecmp(name, "lastdata"))
239                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
240         else if (!strcasecmp(name, "start"))
241                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
242         else if (!strcasecmp(name, "answer"))
243                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
244         else if (!strcasecmp(name, "end"))
245                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
246         else if (!strcasecmp(name, "duration"))
247                 snprintf(workspace, workspacelen, "%ld", cdr->duration ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
248         else if (!strcasecmp(name, "billsec"))
249                 snprintf(workspace, workspacelen, "%ld", cdr->billsec || cdr->answer.tv_sec == 0 ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
250         else if (!strcasecmp(name, "disposition")) {
251                 if (raw) {
252                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
253                 } else {
254                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
255                 }
256         } else if (!strcasecmp(name, "amaflags")) {
257                 if (raw) {
258                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
259                 } else {
260                         ast_copy_string(workspace, ast_cdr_flags2str(cdr->amaflags), workspacelen);
261                 }
262         } else if (!strcasecmp(name, "accountcode"))
263                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
264         else if (!strcasecmp(name, "uniqueid"))
265                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
266         else if (!strcasecmp(name, "userfield"))
267                 ast_copy_string(workspace, cdr->userfield, workspacelen);
268         else if ((varbuf = ast_cdr_getvar_internal(cdr, name, recur)))
269                 ast_copy_string(workspace, varbuf, workspacelen);
270         else
271                 workspace[0] = '\0';
272
273         if (!ast_strlen_zero(workspace))
274                 *ret = workspace;
275 }
276
277 /* readonly cdr variables */
278 static  const char *cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
279                                     "lastapp", "lastdata", "start", "answer", "end", "duration",
280                                     "billsec", "disposition", "amaflags", "accountcode", "uniqueid",
281                                     "userfield", NULL };
282 /*! Set a CDR channel variable 
283         \note You can't set the CDR variables that belong to the actual CDR record, like "billsec".
284 */
285 int ast_cdr_setvar(struct ast_cdr *cdr, const char *name, const char *value, int recur) 
286 {
287         struct ast_var_t *newvariable;
288         struct varshead *headp;
289         int x;
290         
291         if (!cdr)  /* don't die if the cdr is null */
292                 return -1;
293         
294         for (x = 0; cdr_readonly_vars[x]; x++) {
295                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
296                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!.\n", name);
297                         return -1;
298                 }
299         }
300
301         if (!cdr) {
302                 ast_log(LOG_ERROR, "Attempt to set a variable on a nonexistent CDR record.\n");
303                 return -1;
304         }
305
306         for (; cdr; cdr = recur ? cdr->next : NULL) {
307                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
308                         headp = &cdr->varshead;
309                         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
310                                 if (!strcasecmp(ast_var_name(newvariable), name)) {
311                                         /* there is already such a variable, delete it */
312                                         AST_LIST_REMOVE_CURRENT(entries);
313                                         ast_var_delete(newvariable);
314                                         break;
315                                 }
316                         }
317                         AST_LIST_TRAVERSE_SAFE_END;
318
319                         if (value) {
320                                 newvariable = ast_var_assign(name, value);
321                                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
322                         }
323                 }
324         }
325
326         return 0;
327 }
328
329 int ast_cdr_copy_vars(struct ast_cdr *to_cdr, struct ast_cdr *from_cdr)
330 {
331         struct ast_var_t *variables, *newvariable = NULL;
332         struct varshead *headpa, *headpb;
333         const char *var, *val;
334         int x = 0;
335
336         if (!to_cdr || !from_cdr) /* don't die if one of the pointers is null */
337                 return 0;
338
339         headpa = &from_cdr->varshead;
340         headpb = &to_cdr->varshead;
341
342         AST_LIST_TRAVERSE(headpa,variables,entries) {
343                 if (variables &&
344                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
345                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
346                         newvariable = ast_var_assign(var, val);
347                         AST_LIST_INSERT_HEAD(headpb, newvariable, entries);
348                         x++;
349                 }
350         }
351
352         return x;
353 }
354
355 int ast_cdr_serialize_variables(struct ast_cdr *cdr, struct ast_str **buf, char delim, char sep, int recur) 
356 {
357         struct ast_var_t *variables;
358         const char *var, *val;
359         char *tmp;
360         char workspace[256];
361         int total = 0, x = 0, i;
362
363         (*buf)->used = 0;
364         (*buf)->str[0] = '\0';
365
366         for (; cdr; cdr = recur ? cdr->next : NULL) {
367                 if (++x > 1)
368                         ast_str_append(buf, 0, "\n");
369
370                 AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
371                         if (variables &&
372                             (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
373                             !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
374                                 if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, val, sep) < 0) {
375                                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
376                                         break;
377                                 } else
378                                         total++;
379                         } else 
380                                 break;
381                 }
382
383                 for (i = 0; cdr_readonly_vars[i]; i++) {
384                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
385                         if (!tmp)
386                                 continue;
387                         
388                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep) < 0) {
389                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
390                                 break;
391                         } else
392                                 total++;
393                 }
394         }
395
396         return total;
397 }
398
399
400 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
401 {
402
403         /* clear variables */
404         for (; cdr; cdr = recur ? cdr->next : NULL) {
405                 struct ast_var_t *vardata;
406                 struct varshead *headp = &cdr->varshead;
407                 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
408                         ast_var_delete(vardata);
409         }
410 }
411
412 /*! \brief  print a warning if cdr already posted */
413 static void check_post(struct ast_cdr *cdr)
414 {
415         if (!cdr)
416                 return;
417         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
418                 ast_log(LOG_NOTICE, "CDR on channel '%s' already posted\n", S_OR(cdr->channel, "<unknown>"));
419 }
420
421 void ast_cdr_free(struct ast_cdr *cdr)
422 {
423
424         while (cdr) {
425                 struct ast_cdr *next = cdr->next;
426                 char *chan = S_OR(cdr->channel, "<unknown>");
427                 if (!ast_test_flag(cdr, AST_CDR_FLAG_POSTED) && !ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
428                         ast_log(LOG_NOTICE, "CDR on channel '%s' not posted\n", chan);
429                 if (ast_tvzero(cdr->end))
430                         ast_log(LOG_NOTICE, "CDR on channel '%s' lacks end\n", chan);
431                 if (ast_tvzero(cdr->start))
432                         ast_log(LOG_NOTICE, "CDR on channel '%s' lacks start\n", chan);
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_LOCKED)) {
692                         check_post(cdr);
693                         if (cdr->disposition < AST_CDR_ANSWERED)
694                                 cdr->disposition = AST_CDR_ANSWERED;
695                         if (ast_tvzero(cdr->answer))
696                                 cdr->answer = ast_tvnow();
697                 }
698         }
699 }
700
701 void ast_cdr_busy(struct ast_cdr *cdr)
702 {
703
704         for (; cdr; cdr = cdr->next) {
705                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
706                         check_post(cdr);
707                         if (cdr->disposition < AST_CDR_BUSY)
708                                 cdr->disposition = AST_CDR_BUSY;
709                 }
710         }
711 }
712
713 void ast_cdr_failed(struct ast_cdr *cdr)
714 {
715         for (; cdr; cdr = cdr->next) {
716                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
717                         check_post(cdr);
718                         if (cdr->disposition < AST_CDR_FAILED)
719                                 cdr->disposition = AST_CDR_FAILED;
720                 }
721         }
722 }
723
724 void ast_cdr_noanswer(struct ast_cdr *cdr)
725 {
726         char *chan; 
727
728         while (cdr) {
729                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
730                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
731                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
732                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
733                         if (cdr->disposition < AST_CDR_NOANSWER)
734                                 cdr->disposition = AST_CDR_NOANSWER;
735                 }
736                 cdr = cdr->next;
737         }
738 }
739
740 /* everywhere ast_cdr_disposition is called, it will call ast_cdr_failed() 
741    if ast_cdr_disposition returns a non-zero value */
742
743 int ast_cdr_disposition(struct ast_cdr *cdr, int cause)
744 {
745         int res = 0;
746
747         for (; cdr; cdr = cdr->next) {
748                 switch (cause) {  /* handle all the non failure, busy cases, return 0 not to set disposition,
749                                                         return -1 to set disposition to FAILED */
750                 case AST_CAUSE_BUSY:
751                         ast_cdr_busy(cdr);
752                         break;
753                 case AST_CAUSE_NORMAL:
754                         break;
755                 default:
756                         res = -1;
757                 }
758         }
759         return res;
760 }
761
762 void ast_cdr_setdestchan(struct ast_cdr *cdr, const char *chann)
763 {
764         for (; cdr; cdr = cdr->next) {
765                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
766                         check_post(cdr);
767                         ast_copy_string(cdr->dstchannel, chann, sizeof(cdr->dstchannel));
768                 }
769         }
770 }
771
772 void ast_cdr_setapp(struct ast_cdr *cdr, char *app, char *data)
773 {
774
775         for (; cdr; cdr = cdr->next) {
776                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
777                         check_post(cdr);
778                         ast_copy_string(cdr->lastapp, S_OR(app, ""), sizeof(cdr->lastapp));
779                         ast_copy_string(cdr->lastdata, S_OR(data, ""), sizeof(cdr->lastdata));
780                 }
781         }
782 }
783
784 /* set cid info for one record */
785 static void set_one_cid(struct ast_cdr *cdr, struct ast_channel *c)
786 {
787         /* Grab source from ANI or normal Caller*ID */
788         const char *num = S_OR(c->cid.cid_ani, c->cid.cid_num);
789         if (!cdr)
790                 return;
791         if (!ast_strlen_zero(c->cid.cid_name)) {
792                 if (!ast_strlen_zero(num))      /* both name and number */
793                         snprintf(cdr->clid, sizeof(cdr->clid), "\"%s\" <%s>", c->cid.cid_name, num);
794                 else                            /* only name */
795                         ast_copy_string(cdr->clid, c->cid.cid_name, sizeof(cdr->clid));
796         } else if (!ast_strlen_zero(num)) {     /* only number */
797                 ast_copy_string(cdr->clid, num, sizeof(cdr->clid));
798         } else {                                /* nothing known */
799                 cdr->clid[0] = '\0';
800         }
801         ast_copy_string(cdr->src, S_OR(num, ""), sizeof(cdr->src));
802
803 }
804 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
805 {
806         for (; cdr; cdr = cdr->next) {
807                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
808                         set_one_cid(cdr, c);
809         }
810         return 0;
811 }
812
813 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
814 {
815         char *chan;
816
817         for ( ; cdr ; cdr = cdr->next) {
818                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
819                         chan = S_OR(cdr->channel, "<unknown>");
820                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
821                         set_one_cid(cdr, c);
822
823                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
824                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
825                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
826                         /* Destination information */
827                         ast_copy_string(cdr->dst, S_OR(c->macroexten,c->exten), sizeof(cdr->dst));
828                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext,c->context), sizeof(cdr->dcontext));
829                         /* Unique call identifier */
830                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
831                 }
832         }
833         return 0;
834 }
835
836 void ast_cdr_end(struct ast_cdr *cdr)
837 {
838         for ( ; cdr ; cdr = cdr->next) {
839                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
840                         check_post(cdr);
841                         if (ast_tvzero(cdr->end))
842                                 cdr->end = ast_tvnow();
843                         if (ast_tvzero(cdr->start)) {
844                                 ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", S_OR(cdr->channel, "<unknown>"));
845                                 cdr->disposition = AST_CDR_FAILED;
846                         } else
847                                 cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
848                         cdr->billsec = ast_tvzero(cdr->answer) ? 0 : cdr->end.tv_sec - cdr->answer.tv_sec;
849                 }
850         }
851 }
852
853 char *ast_cdr_disp2str(int disposition)
854 {
855         switch (disposition) {
856         case AST_CDR_NULL:
857                 return "NO ANSWER"; /* by default, for backward compatibility */
858         case AST_CDR_NOANSWER:
859                 return "NO ANSWER";
860         case AST_CDR_FAILED:
861                 return "FAILED";                
862         case AST_CDR_BUSY:
863                 return "BUSY";          
864         case AST_CDR_ANSWERED:
865                 return "ANSWERED";
866         }
867         return "UNKNOWN";
868 }
869
870 /*! Converts AMA flag to printable string */
871 char *ast_cdr_flags2str(int flag)
872 {
873         switch (flag) {
874         case AST_CDR_OMIT:
875                 return "OMIT";
876         case AST_CDR_BILLING:
877                 return "BILLING";
878         case AST_CDR_DOCUMENTATION:
879                 return "DOCUMENTATION";
880         }
881         return "Unknown";
882 }
883
884 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
885 {
886         struct ast_cdr *cdr = chan->cdr;
887         char buf[BUFSIZ/2] = "";
888         if (!ast_strlen_zero(chan->accountcode))
889                 ast_copy_string(buf, chan->accountcode, sizeof(buf));
890
891         ast_string_field_set(chan, accountcode, account);
892         for ( ; cdr ; cdr = cdr->next) {
893                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
894                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
895                 }
896         }
897
898         /* Signal change of account code to manager */
899         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);
900         return 0;
901 }
902
903 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
904 {
905         struct ast_cdr *cdr;
906         int newflag = ast_cdr_amaflags2int(flag);
907         if (newflag) {
908                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
909                         if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
910                                 cdr->amaflags = newflag;
911                         }
912                 }
913         }
914
915         return 0;
916 }
917
918 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
919 {
920         struct ast_cdr *cdr = chan->cdr;
921
922         for ( ; cdr ; cdr = cdr->next) {
923                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
924                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
925         }
926
927         return 0;
928 }
929
930 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
931 {
932         struct ast_cdr *cdr = chan->cdr;
933
934         for ( ; cdr ; cdr = cdr->next) {
935                 int len = strlen(cdr->userfield);
936
937                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
938                         ast_copy_string(cdr->userfield + len, userfield, sizeof(cdr->userfield) - len);
939         }
940
941         return 0;
942 }
943
944 int ast_cdr_update(struct ast_channel *c)
945 {
946         struct ast_cdr *cdr = c->cdr;
947
948         for ( ; cdr ; cdr = cdr->next) {
949                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
950                         set_one_cid(cdr, c);
951
952                         /* Copy account code et-al */   
953                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
954                         
955                         /* Destination information */ /* XXX privilege macro* ? */
956                         ast_copy_string(cdr->dst, S_OR(c->macroexten, c->exten), sizeof(cdr->dst));
957                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext, c->context), sizeof(cdr->dcontext));
958                 }
959         }
960
961         return 0;
962 }
963
964 int ast_cdr_amaflags2int(const char *flag)
965 {
966         if (!strcasecmp(flag, "default"))
967                 return 0;
968         if (!strcasecmp(flag, "omit"))
969                 return AST_CDR_OMIT;
970         if (!strcasecmp(flag, "billing"))
971                 return AST_CDR_BILLING;
972         if (!strcasecmp(flag, "documentation"))
973                 return AST_CDR_DOCUMENTATION;
974         return -1;
975 }
976
977 static void post_cdr(struct ast_cdr *cdr)
978 {
979         char *chan;
980         struct ast_cdr_beitem *i;
981
982         for ( ; cdr ; cdr = cdr->next) {
983                 if (!unanswered && cdr->disposition < AST_CDR_ANSWERED && (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
984                         /* For people, who don't want to see unanswered single-channel events */
985                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
986                         continue;
987                 }
988
989                 chan = S_OR(cdr->channel, "<unknown>");
990                 check_post(cdr);
991                 if (ast_tvzero(cdr->end))
992                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
993                 if (ast_tvzero(cdr->start))
994                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
995                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
996                 if (ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
997                         continue;
998                 AST_RWLIST_RDLOCK(&be_list);
999                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
1000                         i->be(cdr);
1001                 }
1002                 AST_RWLIST_UNLOCK(&be_list);
1003         }
1004 }
1005
1006 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
1007 {
1008         struct ast_cdr *dup;
1009         struct ast_flags flags = { 0 };
1010
1011         if (_flags)
1012                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
1013
1014         for ( ; cdr ; cdr = cdr->next) {
1015                 /* Detach if post is requested */
1016                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1017                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
1018                                 ast_cdr_end(cdr);
1019                                 if ((dup = ast_cdr_dup(cdr))) {
1020                                         ast_cdr_detach(dup);
1021                                 }
1022                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
1023                         }
1024
1025                         /* enable CDR only */
1026                         if (ast_test_flag(&flags, AST_CDR_FLAG_POST_ENABLE)) {
1027                                 ast_clear_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1028                                 continue;
1029                         }
1030
1031                         /* clear variables */
1032                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
1033                                 ast_cdr_free_vars(cdr, 0);
1034                         }
1035
1036                         /* Reset to initial state */
1037                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
1038                         memset(&cdr->start, 0, sizeof(cdr->start));
1039                         memset(&cdr->end, 0, sizeof(cdr->end));
1040                         memset(&cdr->answer, 0, sizeof(cdr->answer));
1041                         cdr->billsec = 0;
1042                         cdr->duration = 0;
1043                         ast_cdr_start(cdr);
1044                         cdr->disposition = AST_CDR_NULL;
1045                 }
1046         }
1047 }
1048
1049 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
1050 {
1051         struct ast_cdr *ret;
1052
1053         if (cdr) {
1054                 ret = cdr;
1055
1056                 while (cdr->next)
1057                         cdr = cdr->next;
1058                 cdr->next = newcdr;
1059         } else {
1060                 ret = newcdr;
1061         }
1062
1063         return ret;
1064 }
1065
1066 /*! \note Don't call without cdr_batch_lock */
1067 static void reset_batch(void)
1068 {
1069         batch->size = 0;
1070         batch->head = NULL;
1071         batch->tail = NULL;
1072 }
1073
1074 /*! \note Don't call without cdr_batch_lock */
1075 static int init_batch(void)
1076 {
1077         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
1078         if (!(batch = ast_malloc(sizeof(*batch))))
1079                 return -1;
1080
1081         reset_batch();
1082
1083         return 0;
1084 }
1085
1086 static void *do_batch_backend_process(void *data)
1087 {
1088         struct ast_cdr_batch_item *processeditem;
1089         struct ast_cdr_batch_item *batchitem = data;
1090
1091         /* Push each CDR into storage mechanism(s) and free all the memory */
1092         while (batchitem) {
1093                 post_cdr(batchitem->cdr);
1094                 ast_cdr_free(batchitem->cdr);
1095                 processeditem = batchitem;
1096                 batchitem = batchitem->next;
1097                 ast_free(processeditem);
1098         }
1099
1100         return NULL;
1101 }
1102
1103 void ast_cdr_submit_batch(int shutdown)
1104 {
1105         struct ast_cdr_batch_item *oldbatchitems = NULL;
1106         pthread_t batch_post_thread = AST_PTHREADT_NULL;
1107
1108         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
1109         if (!batch || !batch->head)
1110                 return;
1111
1112         /* move the old CDRs aside, and prepare a new CDR batch */
1113         ast_mutex_lock(&cdr_batch_lock);
1114         oldbatchitems = batch->head;
1115         reset_batch();
1116         ast_mutex_unlock(&cdr_batch_lock);
1117
1118         /* if configured, spawn a new thread to post these CDRs,
1119            also try to save as much as possible if we are shutting down safely */
1120         if (batchscheduleronly || shutdown) {
1121                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
1122                 do_batch_backend_process(oldbatchitems);
1123         } else {
1124                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
1125                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
1126                         do_batch_backend_process(oldbatchitems);
1127                 } else {
1128                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
1129                 }
1130         }
1131 }
1132
1133 static int submit_scheduled_batch(const void *data)
1134 {
1135         ast_cdr_submit_batch(0);
1136         /* manually reschedule from this point in time */
1137         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1138         /* returning zero so the scheduler does not automatically reschedule */
1139         return 0;
1140 }
1141
1142 static void submit_unscheduled_batch(void)
1143 {
1144         /* this is okay since we are not being called from within the scheduler */
1145         AST_SCHED_DEL(sched, cdr_sched);
1146         /* schedule the submission to occur ASAP (1 ms) */
1147         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
1148         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
1149         ast_mutex_lock(&cdr_pending_lock);
1150         ast_cond_signal(&cdr_pending_cond);
1151         ast_mutex_unlock(&cdr_pending_lock);
1152 }
1153
1154 void ast_cdr_detach(struct ast_cdr *cdr)
1155 {
1156         struct ast_cdr_batch_item *newtail;
1157         int curr;
1158
1159         if (!cdr)
1160                 return;
1161
1162         /* maybe they disabled CDR stuff completely, so just drop it */
1163         if (!enabled) {
1164                 ast_debug(1, "Dropping CDR !\n");
1165                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1166                 ast_cdr_free(cdr);
1167                 return;
1168         }
1169
1170         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
1171         if (!batchmode) {
1172                 post_cdr(cdr);
1173                 ast_cdr_free(cdr);
1174                 return;
1175         }
1176
1177         /* otherwise, each CDR gets put into a batch list (at the end) */
1178         ast_debug(1, "CDR detaching from this thread\n");
1179
1180         /* we'll need a new tail for every CDR */
1181         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
1182                 post_cdr(cdr);
1183                 ast_cdr_free(cdr);
1184                 return;
1185         }
1186
1187         /* don't traverse a whole list (just keep track of the tail) */
1188         ast_mutex_lock(&cdr_batch_lock);
1189         if (!batch)
1190                 init_batch();
1191         if (!batch->head) {
1192                 /* new batch is empty, so point the head at the new tail */
1193                 batch->head = newtail;
1194         } else {
1195                 /* already got a batch with something in it, so just append a new tail */
1196                 batch->tail->next = newtail;
1197         }
1198         newtail->cdr = cdr;
1199         batch->tail = newtail;
1200         curr = batch->size++;
1201         ast_mutex_unlock(&cdr_batch_lock);
1202
1203         /* if we have enough stuff to post, then do it */
1204         if (curr >= (batchsize - 1))
1205                 submit_unscheduled_batch();
1206 }
1207
1208 static void *do_cdr(void *data)
1209 {
1210         struct timespec timeout;
1211         int schedms;
1212         int numevents = 0;
1213
1214         for (;;) {
1215                 struct timeval now;
1216                 schedms = ast_sched_wait(sched);
1217                 /* this shouldn't happen, but provide a 1 second default just in case */
1218                 if (schedms <= 0)
1219                         schedms = 1000;
1220                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
1221                 timeout.tv_sec = now.tv_sec;
1222                 timeout.tv_nsec = now.tv_usec * 1000;
1223                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
1224                 ast_mutex_lock(&cdr_pending_lock);
1225                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
1226                 numevents = ast_sched_runq(sched);
1227                 ast_mutex_unlock(&cdr_pending_lock);
1228                 ast_debug(2, "Processed %d scheduled CDR batches from the run queue\n", numevents);
1229         }
1230
1231         return NULL;
1232 }
1233
1234 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1235 {
1236         struct ast_cdr_beitem *beitem=NULL;
1237         int cnt=0;
1238         long nextbatchtime=0;
1239
1240         switch (cmd) {
1241         case CLI_INIT:
1242                 e->command = "cdr show status";
1243                 e->usage = 
1244                         "Usage: cdr show status\n"
1245                         "       Displays the Call Detail Record engine system status.\n";
1246                 return NULL;
1247         case CLI_GENERATE:
1248                 return NULL;
1249         }
1250
1251         if (a->argc > 3)
1252                 return CLI_SHOWUSAGE;
1253
1254         ast_cli(a->fd, "CDR logging: %s\n", enabled ? "enabled" : "disabled");
1255         ast_cli(a->fd, "CDR mode: %s\n", batchmode ? "batch" : "simple");
1256         if (enabled) {
1257                 ast_cli(a->fd, "CDR output unanswered calls: %s\n", unanswered ? "yes" : "no");
1258                 if (batchmode) {
1259                         if (batch)
1260                                 cnt = batch->size;
1261                         if (cdr_sched > -1)
1262                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
1263                         ast_cli(a->fd, "CDR safe shut down: %s\n", batchsafeshutdown ? "enabled" : "disabled");
1264                         ast_cli(a->fd, "CDR batch threading model: %s\n", batchscheduleronly ? "scheduler only" : "scheduler plus separate threads");
1265                         ast_cli(a->fd, "CDR current batch size: %d record%s\n", cnt, ESS(cnt));
1266                         ast_cli(a->fd, "CDR maximum batch size: %d record%s\n", batchsize, ESS(batchsize));
1267                         ast_cli(a->fd, "CDR maximum batch time: %d second%s\n", batchtime, ESS(batchtime));
1268                         ast_cli(a->fd, "CDR next scheduled batch processing time: %ld second%s\n", nextbatchtime, ESS(nextbatchtime));
1269                 }
1270                 AST_RWLIST_RDLOCK(&be_list);
1271                 AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
1272                         ast_cli(a->fd, "CDR registered backend: %s\n", beitem->name);
1273                 }
1274                 AST_RWLIST_UNLOCK(&be_list);
1275         }
1276
1277         return CLI_SUCCESS;
1278 }
1279
1280 static char *handle_cli_status_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1281 {
1282         char *res = handle_cli_status(e, cmd, a);
1283         if (cmd == CLI_INIT)
1284                 e->command = "cdr status";
1285         return res;
1286 }
1287
1288 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1289 {
1290         switch (cmd) {
1291         case CLI_INIT:
1292                 e->command = "cdr submit";
1293                 e->usage = 
1294                         "Usage: cdr submit\n"
1295                         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n";
1296                 return NULL;
1297         case CLI_GENERATE:
1298                 return NULL;
1299         }
1300         if (a->argc > 2)
1301                 return CLI_SHOWUSAGE;
1302
1303         submit_unscheduled_batch();
1304         ast_cli(a->fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1305
1306         return CLI_SUCCESS;
1307 }
1308
1309 static struct ast_cli_entry cli_submit = AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data");
1310 static struct ast_cli_entry cli_status_deprecated = AST_CLI_DEFINE(handle_cli_status_deprecated, "Display the CDR status");
1311 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CDR status", .deprecate_cmd = &cli_status_deprecated);
1312
1313 static int do_reload(int reload)
1314 {
1315         struct ast_config *config;
1316         const char *enabled_value;
1317         const char *unanswered_value;
1318         const char *batched_value;
1319         const char *scheduleronly_value;
1320         const char *batchsafeshutdown_value;
1321         const char *size_value;
1322         const char *time_value;
1323         const char *end_before_h_value;
1324         int cfg_size;
1325         int cfg_time;
1326         int was_enabled;
1327         int was_batchmode;
1328         int res=0;
1329         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1330
1331         if ((config = ast_config_load("cdr.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
1332                 return 0;
1333
1334         ast_mutex_lock(&cdr_batch_lock);
1335
1336         batchsize = BATCH_SIZE_DEFAULT;
1337         batchtime = BATCH_TIME_DEFAULT;
1338         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1339         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1340         was_enabled = enabled;
1341         was_batchmode = batchmode;
1342         enabled = 1;
1343         batchmode = 0;
1344
1345         /* don't run the next scheduled CDR posting while reloading */
1346         AST_SCHED_DEL(sched, cdr_sched);
1347
1348         if (config) {
1349                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1350                         enabled = ast_true(enabled_value);
1351                 }
1352                 if ((unanswered_value = ast_variable_retrieve(config, "general", "unanswered"))) {
1353                         unanswered = ast_true(unanswered_value);
1354                 }
1355                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1356                         batchmode = ast_true(batched_value);
1357                 }
1358                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1359                         batchscheduleronly = ast_true(scheduleronly_value);
1360                 }
1361                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1362                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1363                 }
1364                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1365                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1366                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1367                         else if (size_value < 0)
1368                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1369                         else
1370                                 batchsize = cfg_size;
1371                 }
1372                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1373                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1374                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1375                         else if (time_value < 0)
1376                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1377                         else
1378                                 batchtime = cfg_time;
1379                 }
1380                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1381                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN);
1382         }
1383
1384         if (enabled && !batchmode) {
1385                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1386         } else if (enabled && batchmode) {
1387                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1388                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1389         } else {
1390                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1391         }
1392
1393         /* if this reload enabled the CDR batch mode, create the background thread
1394            if it does not exist */
1395         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1396                 ast_cond_init(&cdr_pending_cond, NULL);
1397                 if (ast_pthread_create_background(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1398                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1399                         AST_SCHED_DEL(sched, cdr_sched);
1400                 } else {
1401                         ast_cli_register(&cli_submit);
1402                         ast_register_atexit(ast_cdr_engine_term);
1403                         res = 0;
1404                 }
1405         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1406            kill it */
1407         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1408                 /* wake up the thread so it will exit */
1409                 pthread_cancel(cdr_thread);
1410                 pthread_kill(cdr_thread, SIGURG);
1411                 pthread_join(cdr_thread, NULL);
1412                 cdr_thread = AST_PTHREADT_NULL;
1413                 ast_cond_destroy(&cdr_pending_cond);
1414                 ast_cli_unregister(&cli_submit);
1415                 ast_unregister_atexit(ast_cdr_engine_term);
1416                 res = 0;
1417                 /* if leaving batch mode, then post the CDRs in the batch,
1418                    and don't reschedule, since we are stopping CDR logging */
1419                 if (!batchmode && was_batchmode) {
1420                         ast_cdr_engine_term();
1421                 }
1422         } else {
1423                 res = 0;
1424         }
1425
1426         ast_mutex_unlock(&cdr_batch_lock);
1427         ast_config_destroy(config);
1428         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: CDR\r\nMessage: CDR subsystem reload requested\r\n");
1429
1430         return res;
1431 }
1432
1433 int ast_cdr_engine_init(void)
1434 {
1435         int res;
1436
1437         sched = sched_context_create();
1438         if (!sched) {
1439                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1440                 return -1;
1441         }
1442
1443         ast_cli_register(&cli_status);
1444
1445         res = do_reload(0);
1446         if (res) {
1447                 ast_mutex_lock(&cdr_batch_lock);
1448                 res = init_batch();
1449                 ast_mutex_unlock(&cdr_batch_lock);
1450         }
1451
1452         return res;
1453 }
1454
1455 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1456    hanging up channels, and then again, after the channel hangup timeout expires */
1457 void ast_cdr_engine_term(void)
1458 {
1459         ast_cdr_submit_batch(batchsafeshutdown);
1460 }
1461
1462 int ast_cdr_engine_reload(void)
1463 {
1464         return do_reload(1);
1465 }
1466