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