Merged revisions 118858 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                 if (tv.tv_sec) {
205                         struct ast_tm tm;
206                         
207                         ast_localtime(&tv, &tm, NULL);
208                         ast_strftime(buf, bufsize, fmt, &tm);
209                 }
210         }
211 }
212
213 /*! CDR channel variable retrieval */
214 void ast_cdr_getvar(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int recur, int raw) 
215 {
216         const char *fmt = "%Y-%m-%d %T";
217         const char *varbuf;
218
219         if (!cdr)  /* don't die if the cdr is null */
220                 return;
221
222         *ret = NULL;
223         /* special vars (the ones from the struct ast_cdr when requested by name) 
224            I'd almost say we should convert all the stringed vals to vars */
225
226         if (!strcasecmp(name, "clid"))
227                 ast_copy_string(workspace, cdr->clid, workspacelen);
228         else if (!strcasecmp(name, "src"))
229                 ast_copy_string(workspace, cdr->src, workspacelen);
230         else if (!strcasecmp(name, "dst"))
231                 ast_copy_string(workspace, cdr->dst, workspacelen);
232         else if (!strcasecmp(name, "dcontext"))
233                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
234         else if (!strcasecmp(name, "channel"))
235                 ast_copy_string(workspace, cdr->channel, workspacelen);
236         else if (!strcasecmp(name, "dstchannel"))
237                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
238         else if (!strcasecmp(name, "lastapp"))
239                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
240         else if (!strcasecmp(name, "lastdata"))
241                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
242         else if (!strcasecmp(name, "start"))
243                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
244         else if (!strcasecmp(name, "answer"))
245                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
246         else if (!strcasecmp(name, "end"))
247                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
248         else if (!strcasecmp(name, "duration"))
249                 snprintf(workspace, workspacelen, "%ld", cdr->duration ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
250         else if (!strcasecmp(name, "billsec"))
251                 snprintf(workspace, workspacelen, "%ld", cdr->billsec || cdr->answer.tv_sec == 0 ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
252         else if (!strcasecmp(name, "disposition")) {
253                 if (raw) {
254                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
255                 } else {
256                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
257                 }
258         } else if (!strcasecmp(name, "amaflags")) {
259                 if (raw) {
260                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
261                 } else {
262                         ast_copy_string(workspace, ast_cdr_flags2str(cdr->amaflags), workspacelen);
263                 }
264         } else if (!strcasecmp(name, "accountcode"))
265                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
266         else if (!strcasecmp(name, "uniqueid"))
267                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
268         else if (!strcasecmp(name, "userfield"))
269                 ast_copy_string(workspace, cdr->userfield, workspacelen);
270         else if ((varbuf = ast_cdr_getvar_internal(cdr, name, recur)))
271                 ast_copy_string(workspace, varbuf, workspacelen);
272         else
273                 workspace[0] = '\0';
274
275         if (!ast_strlen_zero(workspace))
276                 *ret = workspace;
277 }
278
279 /* readonly cdr variables */
280 static  const char *cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
281                                     "lastapp", "lastdata", "start", "answer", "end", "duration",
282                                     "billsec", "disposition", "amaflags", "accountcode", "uniqueid",
283                                     "userfield", NULL };
284 /*! Set a CDR channel variable 
285         \note You can't set the CDR variables that belong to the actual CDR record, like "billsec".
286 */
287 int ast_cdr_setvar(struct ast_cdr *cdr, const char *name, const char *value, int recur) 
288 {
289         struct ast_var_t *newvariable;
290         struct varshead *headp;
291         int x;
292         
293         if (!cdr)  /* don't die if the cdr is null */
294                 return -1;
295         
296         for (x = 0; cdr_readonly_vars[x]; x++) {
297                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
298                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!.\n", name);
299                         return -1;
300                 }
301         }
302
303         if (!cdr) {
304                 ast_log(LOG_ERROR, "Attempt to set a variable on a nonexistent CDR record.\n");
305                 return -1;
306         }
307
308         for (; cdr; cdr = recur ? cdr->next : NULL) {
309                 headp = &cdr->varshead;
310                 AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
311                         if (!strcasecmp(ast_var_name(newvariable), name)) {
312                                 /* there is already such a variable, delete it */
313                                 AST_LIST_REMOVE_CURRENT(entries);
314                                 ast_var_delete(newvariable);
315                                 break;
316                         }
317                 }
318                 AST_LIST_TRAVERSE_SAFE_END;
319                 
320                 if (value) {
321                         newvariable = ast_var_assign(name, value);
322                         AST_LIST_INSERT_HEAD(headp, newvariable, entries);
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                         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 */
385                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
386                         if (!tmp)
387                                 continue;
388                         
389                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep) < 0) {
390                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
391                                 break;
392                         } else
393                                 total++;
394                 }
395         }
396
397         return total;
398 }
399
400
401 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
402 {
403
404         /* clear variables */
405         for (; cdr; cdr = recur ? cdr->next : NULL) {
406                 struct ast_var_t *vardata;
407                 struct varshead *headp = &cdr->varshead;
408                 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
409                         ast_var_delete(vardata);
410         }
411 }
412
413 /*! \brief  print a warning if cdr already posted */
414 static void check_post(struct ast_cdr *cdr)
415 {
416         if (!cdr)
417                 return;
418         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
419                 ast_log(LOG_NOTICE, "CDR on channel '%s' already posted\n", S_OR(cdr->channel, "<unknown>"));
420 }
421
422 void ast_cdr_free(struct ast_cdr *cdr)
423 {
424
425         while (cdr) {
426                 struct ast_cdr *next = cdr->next;
427                 char *chan = S_OR(cdr->channel, "<unknown>");
428                 if (!ast_test_flag(cdr, AST_CDR_FLAG_POSTED) && !ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
429                         ast_log(LOG_NOTICE, "CDR on channel '%s' not posted\n", chan);
430                 if (ast_tvzero(cdr->end))
431                         ast_log(LOG_NOTICE, "CDR on channel '%s' lacks end\n", chan);
432                 if (ast_tvzero(cdr->start))
433                         ast_log(LOG_NOTICE, "CDR on channel '%s' lacks start\n", chan);
434
435                 ast_cdr_free_vars(cdr, 0);
436                 ast_free(cdr);
437                 cdr = next;
438         }
439 }
440
441 /*! \brief the same as a cdr_free call, only with no checks; just get rid of it */
442 void ast_cdr_discard(struct ast_cdr *cdr)
443 {
444         while (cdr) {
445                 struct ast_cdr *next = cdr->next;
446
447                 ast_cdr_free_vars(cdr, 0);
448                 ast_free(cdr);
449                 cdr = next;
450         }
451 }
452
453 struct ast_cdr *ast_cdr_alloc(void)
454 {
455         struct ast_cdr *x;
456         x = ast_calloc(1, sizeof(*x));
457         if (!x)
458                 ast_log(LOG_ERROR,"Allocation Failure for a CDR!\n");
459         return x;
460 }
461
462 static void cdr_merge_vars(struct ast_cdr *to, struct ast_cdr *from)
463 {
464         struct ast_var_t *variablesfrom,*variablesto;
465         struct varshead *headpfrom = &to->varshead;
466         struct varshead *headpto = &from->varshead;
467         AST_LIST_TRAVERSE_SAFE_BEGIN(headpfrom, variablesfrom, entries) {
468                 /* for every var in from, stick it in to */
469                 const char *fromvarname, *fromvarval;
470                 const char *tovarname = NULL, *tovarval = NULL;
471                 fromvarname = ast_var_name(variablesfrom);
472                 fromvarval = ast_var_value(variablesfrom);
473                 tovarname = 0;
474
475                 /* now, quick see if that var is in the 'to' cdr already */
476                 AST_LIST_TRAVERSE(headpto, variablesto, entries) {
477
478                         /* now, quick see if that var is in the 'to' cdr already */
479                         if ( strcasecmp(fromvarname, ast_var_name(variablesto)) == 0 ) {
480                                 tovarname = ast_var_name(variablesto);
481                                 tovarval = ast_var_value(variablesto);
482                                 break;
483                         }
484                 }
485                 if (tovarname && strcasecmp(fromvarval,tovarval) != 0) {  /* this message here to see how irritating the userbase finds it */
486                         ast_log(LOG_NOTICE, "Merging CDR's: variable %s value %s dropped in favor of value %s\n", tovarname, fromvarval, tovarval);
487                         continue;
488                 } else if (tovarname && strcasecmp(fromvarval,tovarval) == 0) /* if they are the same, the job is done */
489                         continue;
490
491                 /* rip this var out of the from cdr, and stick it in the to cdr */
492                 AST_LIST_MOVE_CURRENT(headpto, entries);
493         }
494         AST_LIST_TRAVERSE_SAFE_END;
495 }
496
497 void ast_cdr_merge(struct ast_cdr *to, struct ast_cdr *from)
498 {
499         struct ast_cdr *zcdr;
500         struct ast_cdr *lto = NULL;
501         struct ast_cdr *lfrom = NULL;
502         int discard_from = 0;
503         
504         if (!to || !from)
505                 return;
506
507         /* don't merge into locked CDR's -- it's bad business */
508         if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
509                 zcdr = to; /* safety valve? */
510                 while (to->next) {
511                         lto = to;
512                         to = to->next;
513                 }
514                 
515                 if (ast_test_flag(to, AST_CDR_FLAG_LOCKED)) {
516                         ast_log(LOG_WARNING, "Merging into locked CDR... no choice.");
517                         to = zcdr; /* safety-- if all there are is locked CDR's, then.... ?? */
518                         lto = NULL;
519                 }
520         }
521
522         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED)) {
523                 struct ast_cdr *llfrom = NULL;
524                 discard_from = 1;
525                 if (lto) {
526                         /* insert the from stuff after lto */
527                         lto->next = from;
528                         lfrom = from;
529                         while (lfrom && lfrom->next) {
530                                 if (!lfrom->next->next)
531                                         llfrom = lfrom;
532                                 lfrom = lfrom->next; 
533                         }
534                         /* rip off the last entry and put a copy of the to at the end */
535                         llfrom->next = to;
536                         from = lfrom;
537                 } else {
538                         /* save copy of the current *to cdr */
539                         struct ast_cdr tcdr;
540                         memcpy(&tcdr, to, sizeof(tcdr));
541                         /* copy in the locked from cdr */
542                         memcpy(to, from, sizeof(*to));
543                         lfrom = from;
544                         while (lfrom && lfrom->next) {
545                                 if (!lfrom->next->next)
546                                         llfrom = lfrom;
547                                 lfrom = lfrom->next; 
548                         }
549                         from->next = NULL;
550                         /* rip off the last entry and put a copy of the to at the end */
551                         if (llfrom == from)
552                                 to = to->next = ast_cdr_dup(&tcdr);
553                         else
554                                 to = llfrom->next = ast_cdr_dup(&tcdr);
555                         from = lfrom;
556                 }
557         }
558         
559         if (!ast_tvzero(from->start)) {
560                 if (!ast_tvzero(to->start)) {
561                         if (ast_tvcmp(to->start, from->start) > 0 ) {
562                                 to->start = from->start; /* use the earliest time */
563                                 from->start = ast_tv(0,0); /* we actively "steal" these values */
564                         }
565                         /* else nothing to do */
566                 } else {
567                         to->start = from->start;
568                         from->start = ast_tv(0,0); /* we actively "steal" these values */
569                 }
570         }
571         if (!ast_tvzero(from->answer)) {
572                 if (!ast_tvzero(to->answer)) {
573                         if (ast_tvcmp(to->answer, from->answer) > 0 ) {
574                                 to->answer = from->answer; /* use the earliest time */
575                                 from->answer = ast_tv(0,0); /* we actively "steal" these values */
576                         }
577                         /* we got the earliest answer time, so we'll settle for that? */
578                 } else {
579                         to->answer = from->answer;
580                         from->answer = ast_tv(0,0); /* we actively "steal" these values */
581                 }
582         }
583         if (!ast_tvzero(from->end)) {
584                 if (!ast_tvzero(to->end)) {
585                         if (ast_tvcmp(to->end, from->end) < 0 ) {
586                                 to->end = from->end; /* use the latest time */
587                                 from->end = ast_tv(0,0); /* we actively "steal" these values */
588                                 to->duration = to->end.tv_sec - to->start.tv_sec;  /* don't forget to update the duration, billsec, when we set end */
589                                 to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
590                         }
591                         /* else, nothing to do */
592                 } else {
593                         to->end = from->end;
594                         from->end = ast_tv(0,0); /* we actively "steal" these values */
595                         to->duration = to->end.tv_sec - to->start.tv_sec;
596                         to->billsec = ast_tvzero(to->answer) ? 0 : to->end.tv_sec - to->answer.tv_sec;
597                 }
598         }
599         if (to->disposition < from->disposition) {
600                 to->disposition = from->disposition;
601                 from->disposition = AST_CDR_NOANSWER;
602         }
603         if (ast_strlen_zero(to->lastapp) && !ast_strlen_zero(from->lastapp)) {
604                 ast_copy_string(to->lastapp, from->lastapp, sizeof(to->lastapp));
605                 from->lastapp[0] = 0; /* theft */
606         }
607         if (ast_strlen_zero(to->lastdata) && !ast_strlen_zero(from->lastdata)) {
608                 ast_copy_string(to->lastdata, from->lastdata, sizeof(to->lastdata));
609                 from->lastdata[0] = 0; /* theft */
610         }
611         if (ast_strlen_zero(to->dcontext) && !ast_strlen_zero(from->dcontext)) {
612                 ast_copy_string(to->dcontext, from->dcontext, sizeof(to->dcontext));
613                 from->dcontext[0] = 0; /* theft */
614         }
615         if (ast_strlen_zero(to->dstchannel) && !ast_strlen_zero(from->dstchannel)) {
616                 ast_copy_string(to->dstchannel, from->dstchannel, sizeof(to->dstchannel));
617                 from->dstchannel[0] = 0; /* theft */
618         }
619         if (!ast_strlen_zero(from->channel) && (ast_strlen_zero(to->channel) || !strncasecmp(from->channel, "Agent/", 6))) {
620                 ast_copy_string(to->channel, from->channel, sizeof(to->channel));
621                 from->channel[0] = 0; /* theft */
622         }
623         if (ast_strlen_zero(to->src) && !ast_strlen_zero(from->src)) {
624                 ast_copy_string(to->src, from->src, sizeof(to->src));
625                 from->src[0] = 0; /* theft */
626         }
627         if (ast_strlen_zero(to->clid) && !ast_strlen_zero(from->clid)) {
628                 ast_copy_string(to->clid, from->clid, sizeof(to->clid));
629                 from->clid[0] = 0; /* theft */
630         }
631         if (ast_strlen_zero(to->dst) && !ast_strlen_zero(from->dst)) {
632                 ast_copy_string(to->dst, from->dst, sizeof(to->dst));
633                 from->dst[0] = 0; /* theft */
634         }
635         if (!to->amaflags)
636                 to->amaflags = AST_CDR_DOCUMENTATION;
637         if (!from->amaflags)
638                 from->amaflags = AST_CDR_DOCUMENTATION; /* make sure both amaflags are set to something (DOC is default) */
639         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (to->amaflags == AST_CDR_DOCUMENTATION && from->amaflags != AST_CDR_DOCUMENTATION)) {
640                 to->amaflags = from->amaflags;
641         }
642         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->accountcode) && !ast_strlen_zero(from->accountcode))) {
643                 ast_copy_string(to->accountcode, from->accountcode, sizeof(to->accountcode));
644         }
645         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED) || (ast_strlen_zero(to->userfield) && !ast_strlen_zero(from->userfield))) {
646                 ast_copy_string(to->userfield, from->userfield, sizeof(to->userfield));
647         }
648         /* flags, varsead, ? */
649         cdr_merge_vars(from, to);
650
651         if (ast_test_flag(from, AST_CDR_FLAG_KEEP_VARS))
652                 ast_set_flag(to, AST_CDR_FLAG_KEEP_VARS);
653         if (ast_test_flag(from, AST_CDR_FLAG_POSTED))
654                 ast_set_flag(to, AST_CDR_FLAG_POSTED);
655         if (ast_test_flag(from, AST_CDR_FLAG_LOCKED))
656                 ast_set_flag(to, AST_CDR_FLAG_LOCKED);
657         if (ast_test_flag(from, AST_CDR_FLAG_CHILD))
658                 ast_set_flag(to, AST_CDR_FLAG_CHILD);
659         if (ast_test_flag(from, AST_CDR_FLAG_POST_DISABLED))
660                 ast_set_flag(to, AST_CDR_FLAG_POST_DISABLED);
661
662         /* last, but not least, we need to merge any forked CDRs to the 'to' cdr */
663         while (from->next) {
664                 /* just rip 'em off the 'from' and insert them on the 'to' */
665                 zcdr = from->next;
666                 from->next = zcdr->next;
667                 zcdr->next = NULL;
668                 /* zcdr is now ripped from the current list; */
669                 ast_cdr_append(to, zcdr);
670         }
671         if (discard_from)
672                 ast_cdr_discard(from);
673 }
674
675 void ast_cdr_start(struct ast_cdr *cdr)
676 {
677         char *chan; 
678
679         for (; cdr; cdr = cdr->next) {
680                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
681                         chan = S_OR(cdr->channel, "<unknown>");
682                         check_post(cdr);
683                         cdr->start = ast_tvnow();
684                 }
685         }
686 }
687
688 void ast_cdr_answer(struct ast_cdr *cdr)
689 {
690
691         for (; cdr; cdr = cdr->next) {
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 void ast_cdr_busy(struct ast_cdr *cdr)
701 {
702
703         for (; cdr; cdr = cdr->next) {
704                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
705                         check_post(cdr);
706                         if (cdr->disposition < AST_CDR_BUSY)
707                                 cdr->disposition = AST_CDR_BUSY;
708                 }
709         }
710 }
711
712 void ast_cdr_failed(struct ast_cdr *cdr)
713 {
714         for (; cdr; cdr = cdr->next) {
715                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
716                         check_post(cdr);
717                         if (cdr->disposition < AST_CDR_FAILED)
718                                 cdr->disposition = AST_CDR_FAILED;
719                 }
720         }
721 }
722
723 void ast_cdr_noanswer(struct ast_cdr *cdr)
724 {
725         char *chan; 
726
727         while (cdr) {
728                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
729                         chan = !ast_strlen_zero(cdr->channel) ? cdr->channel : "<unknown>";
730                         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
731                                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", chan);
732                         if (cdr->disposition < AST_CDR_NOANSWER)
733                                 cdr->disposition = AST_CDR_NOANSWER;
734                 }
735                 cdr = cdr->next;
736         }
737 }
738
739 /* everywhere ast_cdr_disposition is called, it will call ast_cdr_failed() 
740    if ast_cdr_disposition returns a non-zero value */
741
742 int ast_cdr_disposition(struct ast_cdr *cdr, int cause)
743 {
744         int res = 0;
745
746         for (; cdr; cdr = cdr->next) {
747                 switch (cause) {  /* handle all the non failure, busy cases, return 0 not to set disposition,
748                                                         return -1 to set disposition to FAILED */
749                 case AST_CAUSE_BUSY:
750                         ast_cdr_busy(cdr);
751                         break;
752                 case AST_CAUSE_NORMAL:
753                         break;
754                 default:
755                         res = -1;
756                 }
757         }
758         return res;
759 }
760
761 void ast_cdr_setdestchan(struct ast_cdr *cdr, const char *chann)
762 {
763         for (; cdr; cdr = cdr->next) {
764                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
765                         check_post(cdr);
766                         ast_copy_string(cdr->dstchannel, chann, sizeof(cdr->dstchannel));
767                 }
768         }
769 }
770
771 void ast_cdr_setapp(struct ast_cdr *cdr, char *app, char *data)
772 {
773
774         for (; cdr; cdr = cdr->next) {
775                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
776                         check_post(cdr);
777                         ast_copy_string(cdr->lastapp, S_OR(app, ""), sizeof(cdr->lastapp));
778                         ast_copy_string(cdr->lastdata, S_OR(data, ""), sizeof(cdr->lastdata));
779                 }
780         }
781 }
782
783 /* set cid info for one record */
784 static void set_one_cid(struct ast_cdr *cdr, struct ast_channel *c)
785 {
786         /* Grab source from ANI or normal Caller*ID */
787         const char *num = S_OR(c->cid.cid_ani, c->cid.cid_num);
788         if (!cdr)
789                 return;
790         if (!ast_strlen_zero(c->cid.cid_name)) {
791                 if (!ast_strlen_zero(num))      /* both name and number */
792                         snprintf(cdr->clid, sizeof(cdr->clid), "\"%s\" <%s>", c->cid.cid_name, num);
793                 else                            /* only name */
794                         ast_copy_string(cdr->clid, c->cid.cid_name, sizeof(cdr->clid));
795         } else if (!ast_strlen_zero(num)) {     /* only number */
796                 ast_copy_string(cdr->clid, num, sizeof(cdr->clid));
797         } else {                                /* nothing known */
798                 cdr->clid[0] = '\0';
799         }
800         ast_copy_string(cdr->src, S_OR(num, ""), sizeof(cdr->src));
801
802 }
803 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
804 {
805         for (; cdr; cdr = cdr->next) {
806                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
807                         set_one_cid(cdr, c);
808         }
809         return 0;
810 }
811
812 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
813 {
814         char *chan;
815
816         for ( ; cdr ; cdr = cdr->next) {
817                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
818                         chan = S_OR(cdr->channel, "<unknown>");
819                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
820                         set_one_cid(cdr, c);
821
822                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
823                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
824                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
825                         /* Destination information */
826                         ast_copy_string(cdr->dst, S_OR(c->macroexten,c->exten), sizeof(cdr->dst));
827                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext,c->context), sizeof(cdr->dcontext));
828                         /* Unique call identifier */
829                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
830                 }
831         }
832         return 0;
833 }
834
835 /* Three routines were "fixed" via 10668, and later shown that 
836    users were depending on this behavior. ast_cdr_end,
837    ast_cdr_setvar and ast_cdr_answer are the three routines.
838    While most of the other routines would not touch 
839    LOCKED cdr's, these three routines were designed to
840    operate on locked CDR's as a matter of course.
841    I now appreciate how this plays with the ForkCDR app,
842    which forms these cdr chains in the first place. 
843    cdr_end is pretty key: all cdrs created are closed
844    together. They only vary by start time. Arithmetically,
845    users can calculate the subintervals they wish to track. */
846
847 void ast_cdr_end(struct ast_cdr *cdr)
848 {
849         for ( ; cdr ; cdr = cdr->next) {
850                 check_post(cdr);
851                 if (ast_tvzero(cdr->end))
852                         cdr->end = ast_tvnow();
853                 if (ast_tvzero(cdr->start)) {
854                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", S_OR(cdr->channel, "<unknown>"));
855                         cdr->disposition = AST_CDR_FAILED;
856                 } else
857                         cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
858                 cdr->billsec = ast_tvzero(cdr->answer) ? 0 : cdr->end.tv_sec - cdr->answer.tv_sec;
859         }
860 }
861
862 char *ast_cdr_disp2str(int disposition)
863 {
864         switch (disposition) {
865         case AST_CDR_NULL:
866                 return "NO ANSWER"; /* by default, for backward compatibility */
867         case AST_CDR_NOANSWER:
868                 return "NO ANSWER";
869         case AST_CDR_FAILED:
870                 return "FAILED";                
871         case AST_CDR_BUSY:
872                 return "BUSY";          
873         case AST_CDR_ANSWERED:
874                 return "ANSWERED";
875         }
876         return "UNKNOWN";
877 }
878
879 /*! Converts AMA flag to printable string */
880 char *ast_cdr_flags2str(int flag)
881 {
882         switch (flag) {
883         case AST_CDR_OMIT:
884                 return "OMIT";
885         case AST_CDR_BILLING:
886                 return "BILLING";
887         case AST_CDR_DOCUMENTATION:
888                 return "DOCUMENTATION";
889         }
890         return "Unknown";
891 }
892
893 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
894 {
895         struct ast_cdr *cdr = chan->cdr;
896         char buf[BUFSIZ/2] = "";
897         if (!ast_strlen_zero(chan->accountcode))
898                 ast_copy_string(buf, chan->accountcode, sizeof(buf));
899
900         ast_string_field_set(chan, accountcode, account);
901         for ( ; cdr ; cdr = cdr->next) {
902                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
903                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
904                 }
905         }
906
907         /* Signal change of account code to manager */
908         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);
909         return 0;
910 }
911
912 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
913 {
914         struct ast_cdr *cdr;
915         int newflag = ast_cdr_amaflags2int(flag);
916         if (newflag) {
917                 for (cdr = chan->cdr; cdr; cdr = cdr->next) {
918                         if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
919                                 cdr->amaflags = newflag;
920                         }
921                 }
922         }
923
924         return 0;
925 }
926
927 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
928 {
929         struct ast_cdr *cdr = chan->cdr;
930
931         for ( ; cdr ; cdr = cdr->next) {
932                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
933                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
934         }
935
936         return 0;
937 }
938
939 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
940 {
941         struct ast_cdr *cdr = chan->cdr;
942
943         for ( ; cdr ; cdr = cdr->next) {
944                 int len = strlen(cdr->userfield);
945
946                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
947                         ast_copy_string(cdr->userfield + len, userfield, sizeof(cdr->userfield) - len);
948         }
949
950         return 0;
951 }
952
953 int ast_cdr_update(struct ast_channel *c)
954 {
955         struct ast_cdr *cdr = c->cdr;
956
957         for ( ; cdr ; cdr = cdr->next) {
958                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
959                         set_one_cid(cdr, c);
960
961                         /* Copy account code et-al */   
962                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
963                         
964                         /* Destination information */ /* XXX privilege macro* ? */
965                         ast_copy_string(cdr->dst, S_OR(c->macroexten, c->exten), sizeof(cdr->dst));
966                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext, c->context), sizeof(cdr->dcontext));
967                 }
968         }
969
970         return 0;
971 }
972
973 int ast_cdr_amaflags2int(const char *flag)
974 {
975         if (!strcasecmp(flag, "default"))
976                 return 0;
977         if (!strcasecmp(flag, "omit"))
978                 return AST_CDR_OMIT;
979         if (!strcasecmp(flag, "billing"))
980                 return AST_CDR_BILLING;
981         if (!strcasecmp(flag, "documentation"))
982                 return AST_CDR_DOCUMENTATION;
983         return -1;
984 }
985
986 static void post_cdr(struct ast_cdr *cdr)
987 {
988         char *chan;
989         struct ast_cdr_beitem *i;
990
991         for ( ; cdr ; cdr = cdr->next) {
992                 if (!unanswered && cdr->disposition < AST_CDR_ANSWERED && (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
993                         /* For people, who don't want to see unanswered single-channel events */
994                         ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
995                         continue;
996                 }
997
998                 chan = S_OR(cdr->channel, "<unknown>");
999                 check_post(cdr);
1000                 if (ast_tvzero(cdr->end))
1001                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
1002                 if (ast_tvzero(cdr->start))
1003                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
1004                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
1005                 if (ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
1006                         continue;
1007                 AST_RWLIST_RDLOCK(&be_list);
1008                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
1009                         i->be(cdr);
1010                 }
1011                 AST_RWLIST_UNLOCK(&be_list);
1012         }
1013 }
1014
1015 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
1016 {
1017         struct ast_cdr *dup;
1018         struct ast_flags flags = { 0 };
1019
1020         if (_flags)
1021                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
1022
1023         for ( ; cdr ; cdr = cdr->next) {
1024                 /* Detach if post is requested */
1025                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
1026                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
1027                                 ast_cdr_end(cdr);
1028                                 if ((dup = ast_cdr_dup(cdr))) {
1029                                         ast_cdr_detach(dup);
1030                                 }
1031                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
1032                         }
1033
1034                         /* enable CDR only */
1035                         if (ast_test_flag(&flags, AST_CDR_FLAG_POST_ENABLE)) {
1036                                 ast_clear_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1037                                 continue;
1038                         }
1039
1040                         /* clear variables */
1041                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
1042                                 ast_cdr_free_vars(cdr, 0);
1043                         }
1044
1045                         /* Reset to initial state */
1046                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
1047                         memset(&cdr->start, 0, sizeof(cdr->start));
1048                         memset(&cdr->end, 0, sizeof(cdr->end));
1049                         memset(&cdr->answer, 0, sizeof(cdr->answer));
1050                         cdr->billsec = 0;
1051                         cdr->duration = 0;
1052                         ast_cdr_start(cdr);
1053                         cdr->disposition = AST_CDR_NULL;
1054                 }
1055         }
1056 }
1057
1058 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
1059 {
1060         struct ast_cdr *ret;
1061
1062         if (cdr) {
1063                 ret = cdr;
1064
1065                 while (cdr->next)
1066                         cdr = cdr->next;
1067                 cdr->next = newcdr;
1068         } else {
1069                 ret = newcdr;
1070         }
1071
1072         return ret;
1073 }
1074
1075 /*! \note Don't call without cdr_batch_lock */
1076 static void reset_batch(void)
1077 {
1078         batch->size = 0;
1079         batch->head = NULL;
1080         batch->tail = NULL;
1081 }
1082
1083 /*! \note Don't call without cdr_batch_lock */
1084 static int init_batch(void)
1085 {
1086         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
1087         if (!(batch = ast_malloc(sizeof(*batch))))
1088                 return -1;
1089
1090         reset_batch();
1091
1092         return 0;
1093 }
1094
1095 static void *do_batch_backend_process(void *data)
1096 {
1097         struct ast_cdr_batch_item *processeditem;
1098         struct ast_cdr_batch_item *batchitem = data;
1099
1100         /* Push each CDR into storage mechanism(s) and free all the memory */
1101         while (batchitem) {
1102                 post_cdr(batchitem->cdr);
1103                 ast_cdr_free(batchitem->cdr);
1104                 processeditem = batchitem;
1105                 batchitem = batchitem->next;
1106                 ast_free(processeditem);
1107         }
1108
1109         return NULL;
1110 }
1111
1112 void ast_cdr_submit_batch(int shutdown)
1113 {
1114         struct ast_cdr_batch_item *oldbatchitems = NULL;
1115         pthread_t batch_post_thread = AST_PTHREADT_NULL;
1116
1117         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
1118         if (!batch || !batch->head)
1119                 return;
1120
1121         /* move the old CDRs aside, and prepare a new CDR batch */
1122         ast_mutex_lock(&cdr_batch_lock);
1123         oldbatchitems = batch->head;
1124         reset_batch();
1125         ast_mutex_unlock(&cdr_batch_lock);
1126
1127         /* if configured, spawn a new thread to post these CDRs,
1128            also try to save as much as possible if we are shutting down safely */
1129         if (batchscheduleronly || shutdown) {
1130                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
1131                 do_batch_backend_process(oldbatchitems);
1132         } else {
1133                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
1134                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
1135                         do_batch_backend_process(oldbatchitems);
1136                 } else {
1137                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
1138                 }
1139         }
1140 }
1141
1142 static int submit_scheduled_batch(const void *data)
1143 {
1144         ast_cdr_submit_batch(0);
1145         /* manually reschedule from this point in time */
1146         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1147         /* returning zero so the scheduler does not automatically reschedule */
1148         return 0;
1149 }
1150
1151 static void submit_unscheduled_batch(void)
1152 {
1153         /* this is okay since we are not being called from within the scheduler */
1154         AST_SCHED_DEL(sched, cdr_sched);
1155         /* schedule the submission to occur ASAP (1 ms) */
1156         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
1157         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
1158         ast_mutex_lock(&cdr_pending_lock);
1159         ast_cond_signal(&cdr_pending_cond);
1160         ast_mutex_unlock(&cdr_pending_lock);
1161 }
1162
1163 void ast_cdr_detach(struct ast_cdr *cdr)
1164 {
1165         struct ast_cdr_batch_item *newtail;
1166         int curr;
1167
1168         if (!cdr)
1169                 return;
1170
1171         /* maybe they disabled CDR stuff completely, so just drop it */
1172         if (!enabled) {
1173                 ast_debug(1, "Dropping CDR !\n");
1174                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
1175                 ast_cdr_free(cdr);
1176                 return;
1177         }
1178
1179         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
1180         if (!batchmode) {
1181                 post_cdr(cdr);
1182                 ast_cdr_free(cdr);
1183                 return;
1184         }
1185
1186         /* otherwise, each CDR gets put into a batch list (at the end) */
1187         ast_debug(1, "CDR detaching from this thread\n");
1188
1189         /* we'll need a new tail for every CDR */
1190         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
1191                 post_cdr(cdr);
1192                 ast_cdr_free(cdr);
1193                 return;
1194         }
1195
1196         /* don't traverse a whole list (just keep track of the tail) */
1197         ast_mutex_lock(&cdr_batch_lock);
1198         if (!batch)
1199                 init_batch();
1200         if (!batch->head) {
1201                 /* new batch is empty, so point the head at the new tail */
1202                 batch->head = newtail;
1203         } else {
1204                 /* already got a batch with something in it, so just append a new tail */
1205                 batch->tail->next = newtail;
1206         }
1207         newtail->cdr = cdr;
1208         batch->tail = newtail;
1209         curr = batch->size++;
1210         ast_mutex_unlock(&cdr_batch_lock);
1211
1212         /* if we have enough stuff to post, then do it */
1213         if (curr >= (batchsize - 1))
1214                 submit_unscheduled_batch();
1215 }
1216
1217 static void *do_cdr(void *data)
1218 {
1219         struct timespec timeout;
1220         int schedms;
1221         int numevents = 0;
1222
1223         for (;;) {
1224                 struct timeval now;
1225                 schedms = ast_sched_wait(sched);
1226                 /* this shouldn't happen, but provide a 1 second default just in case */
1227                 if (schedms <= 0)
1228                         schedms = 1000;
1229                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
1230                 timeout.tv_sec = now.tv_sec;
1231                 timeout.tv_nsec = now.tv_usec * 1000;
1232                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
1233                 ast_mutex_lock(&cdr_pending_lock);
1234                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
1235                 numevents = ast_sched_runq(sched);
1236                 ast_mutex_unlock(&cdr_pending_lock);
1237                 ast_debug(2, "Processed %d scheduled CDR batches from the run queue\n", numevents);
1238         }
1239
1240         return NULL;
1241 }
1242
1243 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1244 {
1245         struct ast_cdr_beitem *beitem=NULL;
1246         int cnt=0;
1247         long nextbatchtime=0;
1248
1249         switch (cmd) {
1250         case CLI_INIT:
1251                 e->command = "cdr show status";
1252                 e->usage = 
1253                         "Usage: cdr show status\n"
1254                         "       Displays the Call Detail Record engine system status.\n";
1255                 return NULL;
1256         case CLI_GENERATE:
1257                 return NULL;
1258         }
1259
1260         if (a->argc > 3)
1261                 return CLI_SHOWUSAGE;
1262
1263         ast_cli(a->fd, "CDR logging: %s\n", enabled ? "enabled" : "disabled");
1264         ast_cli(a->fd, "CDR mode: %s\n", batchmode ? "batch" : "simple");
1265         if (enabled) {
1266                 ast_cli(a->fd, "CDR output unanswered calls: %s\n", unanswered ? "yes" : "no");
1267                 if (batchmode) {
1268                         if (batch)
1269                                 cnt = batch->size;
1270                         if (cdr_sched > -1)
1271                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
1272                         ast_cli(a->fd, "CDR safe shut down: %s\n", batchsafeshutdown ? "enabled" : "disabled");
1273                         ast_cli(a->fd, "CDR batch threading model: %s\n", batchscheduleronly ? "scheduler only" : "scheduler plus separate threads");
1274                         ast_cli(a->fd, "CDR current batch size: %d record%s\n", cnt, ESS(cnt));
1275                         ast_cli(a->fd, "CDR maximum batch size: %d record%s\n", batchsize, ESS(batchsize));
1276                         ast_cli(a->fd, "CDR maximum batch time: %d second%s\n", batchtime, ESS(batchtime));
1277                         ast_cli(a->fd, "CDR next scheduled batch processing time: %ld second%s\n", nextbatchtime, ESS(nextbatchtime));
1278                 }
1279                 AST_RWLIST_RDLOCK(&be_list);
1280                 AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
1281                         ast_cli(a->fd, "CDR registered backend: %s\n", beitem->name);
1282                 }
1283                 AST_RWLIST_UNLOCK(&be_list);
1284         }
1285
1286         return CLI_SUCCESS;
1287 }
1288
1289 static char *handle_cli_status_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1290 {
1291         char *res = handle_cli_status(e, cmd, a);
1292         if (cmd == CLI_INIT)
1293                 e->command = "cdr status";
1294         return res;
1295 }
1296
1297 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1298 {
1299         switch (cmd) {
1300         case CLI_INIT:
1301                 e->command = "cdr submit";
1302                 e->usage = 
1303                         "Usage: cdr submit\n"
1304                         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n";
1305                 return NULL;
1306         case CLI_GENERATE:
1307                 return NULL;
1308         }
1309         if (a->argc > 2)
1310                 return CLI_SHOWUSAGE;
1311
1312         submit_unscheduled_batch();
1313         ast_cli(a->fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1314
1315         return CLI_SUCCESS;
1316 }
1317
1318 static struct ast_cli_entry cli_submit = AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data");
1319 static struct ast_cli_entry cli_status_deprecated = AST_CLI_DEFINE(handle_cli_status_deprecated, "Display the CDR status");
1320 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CDR status", .deprecate_cmd = &cli_status_deprecated);
1321
1322 static int do_reload(int reload)
1323 {
1324         struct ast_config *config;
1325         const char *enabled_value;
1326         const char *unanswered_value;
1327         const char *batched_value;
1328         const char *scheduleronly_value;
1329         const char *batchsafeshutdown_value;
1330         const char *size_value;
1331         const char *time_value;
1332         const char *end_before_h_value;
1333         int cfg_size;
1334         int cfg_time;
1335         int was_enabled;
1336         int was_batchmode;
1337         int res=0;
1338         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1339
1340         if ((config = ast_config_load2("cdr.conf", "cdr", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
1341                 return 0;
1342
1343         ast_mutex_lock(&cdr_batch_lock);
1344
1345         batchsize = BATCH_SIZE_DEFAULT;
1346         batchtime = BATCH_TIME_DEFAULT;
1347         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1348         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1349         was_enabled = enabled;
1350         was_batchmode = batchmode;
1351         enabled = 1;
1352         batchmode = 0;
1353
1354         /* don't run the next scheduled CDR posting while reloading */
1355         AST_SCHED_DEL(sched, cdr_sched);
1356
1357         if (config) {
1358                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1359                         enabled = ast_true(enabled_value);
1360                 }
1361                 if ((unanswered_value = ast_variable_retrieve(config, "general", "unanswered"))) {
1362                         unanswered = ast_true(unanswered_value);
1363                 }
1364                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1365                         batchmode = ast_true(batched_value);
1366                 }
1367                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1368                         batchscheduleronly = ast_true(scheduleronly_value);
1369                 }
1370                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1371                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1372                 }
1373                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1374                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1375                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1376                         else if (size_value < 0)
1377                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1378                         else
1379                                 batchsize = cfg_size;
1380                 }
1381                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1382                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1383                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1384                         else if (time_value < 0)
1385                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1386                         else
1387                                 batchtime = cfg_time;
1388                 }
1389                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1390                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN);
1391         }
1392
1393         if (enabled && !batchmode) {
1394                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1395         } else if (enabled && batchmode) {
1396                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1397                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1398         } else {
1399                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1400         }
1401
1402         /* if this reload enabled the CDR batch mode, create the background thread
1403            if it does not exist */
1404         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1405                 ast_cond_init(&cdr_pending_cond, NULL);
1406                 if (ast_pthread_create_background(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1407                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1408                         AST_SCHED_DEL(sched, cdr_sched);
1409                 } else {
1410                         ast_cli_register(&cli_submit);
1411                         ast_register_atexit(ast_cdr_engine_term);
1412                         res = 0;
1413                 }
1414         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1415            kill it */
1416         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1417                 /* wake up the thread so it will exit */
1418                 pthread_cancel(cdr_thread);
1419                 pthread_kill(cdr_thread, SIGURG);
1420                 pthread_join(cdr_thread, NULL);
1421                 cdr_thread = AST_PTHREADT_NULL;
1422                 ast_cond_destroy(&cdr_pending_cond);
1423                 ast_cli_unregister(&cli_submit);
1424                 ast_unregister_atexit(ast_cdr_engine_term);
1425                 res = 0;
1426                 /* if leaving batch mode, then post the CDRs in the batch,
1427                    and don't reschedule, since we are stopping CDR logging */
1428                 if (!batchmode && was_batchmode) {
1429                         ast_cdr_engine_term();
1430                 }
1431         } else {
1432                 res = 0;
1433         }
1434
1435         ast_mutex_unlock(&cdr_batch_lock);
1436         ast_config_destroy(config);
1437         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: CDR\r\nMessage: CDR subsystem reload requested\r\n");
1438
1439         return res;
1440 }
1441
1442 int ast_cdr_engine_init(void)
1443 {
1444         int res;
1445
1446         sched = sched_context_create();
1447         if (!sched) {
1448                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1449                 return -1;
1450         }
1451
1452         ast_cli_register(&cli_status);
1453
1454         res = do_reload(0);
1455         if (res) {
1456                 ast_mutex_lock(&cdr_batch_lock);
1457                 res = init_batch();
1458                 ast_mutex_unlock(&cdr_batch_lock);
1459         }
1460
1461         return res;
1462 }
1463
1464 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1465    hanging up channels, and then again, after the channel hangup timeout expires */
1466 void ast_cdr_engine_term(void)
1467 {
1468         ast_cdr_submit_batch(batchsafeshutdown);
1469 }
1470
1471 int ast_cdr_engine_reload(void)
1472 {
1473         return do_reload(1);
1474 }
1475