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