Don't force context for domain= setting (imported from 1.2)
[asterisk/asterisk.git] / 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_LIST_ENTRY(ast_cdr_beitem) list;
67 };
68
69 static AST_LIST_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;
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
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(char *name, char *desc, ast_cdrbe be)
109 {
110         struct ast_cdr_beitem *i;
111
112         if (!name)
113                 return -1;
114         if (!be) {
115                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
116                 return -1;
117         }
118
119         AST_LIST_LOCK(&be_list);
120         AST_LIST_TRAVERSE(&be_list, i, list) {
121                 if (!strcasecmp(name, i->name))
122                         break;
123         }
124         AST_LIST_UNLOCK(&be_list);
125
126         if (i) {
127                 ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
128                 return -1;
129         }
130
131         if (!(i = ast_calloc(1, sizeof(*i))))   
132                 return -1;
133
134         i->be = be;
135         ast_copy_string(i->name, name, sizeof(i->name));
136         ast_copy_string(i->desc, desc, sizeof(i->desc));
137
138         AST_LIST_LOCK(&be_list);
139         AST_LIST_INSERT_HEAD(&be_list, i, list);
140         AST_LIST_UNLOCK(&be_list);
141
142         return 0;
143 }
144
145 /*! unregister a CDR driver */
146 void ast_cdr_unregister(char *name)
147 {
148         struct ast_cdr_beitem *i = NULL;
149
150         AST_LIST_LOCK(&be_list);
151         AST_LIST_TRAVERSE_SAFE_BEGIN(&be_list, i, list) {
152                 if (!strcasecmp(name, i->name)) {
153                         AST_LIST_REMOVE_CURRENT(&be_list, list);
154                         if (option_verbose > 1)
155                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered '%s' CDR backend\n", name);
156                         free(i);
157                         break;
158                 }
159         }
160         AST_LIST_TRAVERSE_SAFE_END;
161         AST_LIST_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 = ast_cdr_alloc();
170
171         if (!newcdr)
172                 return NULL;
173
174         memcpy(newcdr, cdr, sizeof(*newcdr));
175         /* The varshead is unusable, volatile even, after the memcpy so we take care of that here */
176         memset(&newcdr->varshead, 0, sizeof(newcdr->varshead));
177         ast_cdr_copy_vars(newcdr, cdr);
178         newcdr->next = NULL;
179
180         return newcdr;
181 }
182
183 static const char *ast_cdr_getvar_internal(struct ast_cdr *cdr, const char *name, int recur) 
184 {
185         if (ast_strlen_zero(name))
186                 return NULL;
187
188         for (; cdr; cdr = recur ? cdr->next : NULL) {
189                 struct ast_var_t *variables;
190                 struct varshead *headp = &cdr->varshead;
191                 AST_LIST_TRAVERSE(headp, variables, entries) {
192                         if (!strcasecmp(name, ast_var_name(variables)))
193                                 return ast_var_value(variables);
194                 }
195         }
196
197         return NULL;
198 }
199
200 static void cdr_get_tv(struct timeval tv, const char *fmt, char *buf, int bufsize)
201 {
202         if (fmt == NULL) {      /* raw mode */
203                 snprintf(buf, bufsize, "%ld.%06ld", (long)tv.tv_sec, (long)tv.tv_usec);
204         } else {  
205                 time_t t = tv.tv_sec;
206                 if (t) {
207                         struct tm tm;
208                         localtime_r(&t, &tm);
209                         strftime(buf, bufsize, fmt, &tm);
210                 }
211         }
212 }
213
214 /*! CDR channel variable retrieval */
215 void ast_cdr_getvar(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int recur, int raw) 
216 {
217         const char *fmt = "%Y-%m-%d %T";
218         const char *varbuf;
219
220         *ret = NULL;
221         /* special vars (the ones from the struct ast_cdr when requested by name) 
222            I'd almost say we should convert all the stringed vals to vars */
223
224         if (!strcasecmp(name, "clid"))
225                 ast_copy_string(workspace, cdr->clid, workspacelen);
226         else if (!strcasecmp(name, "src"))
227                 ast_copy_string(workspace, cdr->src, workspacelen);
228         else if (!strcasecmp(name, "dst"))
229                 ast_copy_string(workspace, cdr->dst, workspacelen);
230         else if (!strcasecmp(name, "dcontext"))
231                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
232         else if (!strcasecmp(name, "channel"))
233                 ast_copy_string(workspace, cdr->channel, workspacelen);
234         else if (!strcasecmp(name, "dstchannel"))
235                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
236         else if (!strcasecmp(name, "lastapp"))
237                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
238         else if (!strcasecmp(name, "lastdata"))
239                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
240         else if (!strcasecmp(name, "start"))
241                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
242         else if (!strcasecmp(name, "answer"))
243                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
244         else if (!strcasecmp(name, "end"))
245                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
246         else if (!strcasecmp(name, "duration"))
247                 snprintf(workspace, workspacelen, "%ld", cdr->duration);
248         else if (!strcasecmp(name, "billsec"))
249                 snprintf(workspace, workspacelen, "%ld", cdr->billsec);
250         else if (!strcasecmp(name, "disposition")) {
251                 if (raw) {
252                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
253                 } else {
254                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
255                 }
256         } else if (!strcasecmp(name, "amaflags")) {
257                 if (raw) {
258                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
259                 } else {
260                         ast_copy_string(workspace, ast_cdr_flags2str(cdr->amaflags), workspacelen);
261                 }
262         } else if (!strcasecmp(name, "accountcode"))
263                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
264         else if (!strcasecmp(name, "uniqueid"))
265                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
266         else if (!strcasecmp(name, "userfield"))
267                 ast_copy_string(workspace, cdr->userfield, workspacelen);
268         else if ((varbuf = ast_cdr_getvar_internal(cdr, name, recur)))
269                 ast_copy_string(workspace, varbuf, workspacelen);
270
271         if (!ast_strlen_zero(workspace))
272                 *ret = workspace;
273 }
274
275 /* readonly cdr variables */
276 static  const char *cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
277                                     "lastapp", "lastdata", "start", "answer", "end", "duration",
278                                     "billsec", "disposition", "amaflags", "accountcode", "uniqueid",
279                                     "userfield", NULL };
280 /*! Set a CDR channel variable 
281         \note You can't set the CDR variables that belong to the actual CDR record, like "billsec".
282 */
283 int ast_cdr_setvar(struct ast_cdr *cdr, const char *name, const char *value, int recur) 
284 {
285         struct ast_var_t *newvariable;
286         struct varshead *headp;
287         int x;
288         
289         for(x = 0; cdr_readonly_vars[x]; x++) {
290                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
291                         ast_log(LOG_ERROR, "Attempt to set a read-only variable!.\n");
292                         return -1;
293                 }
294         }
295
296         if (!cdr) {
297                 ast_log(LOG_ERROR, "Attempt to set a variable on a nonexistent CDR record.\n");
298                 return -1;
299         }
300
301         for (; cdr; cdr = recur ? cdr->next : NULL) {
302                 headp = &cdr->varshead;
303                 AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
304                         if (!strcasecmp(ast_var_name(newvariable), name)) {
305                                 /* there is already such a variable, delete it */
306                                 AST_LIST_REMOVE_CURRENT(headp, entries);
307                                 ast_var_delete(newvariable);
308                                 break;
309                         }
310                 }
311                 AST_LIST_TRAVERSE_SAFE_END;
312
313                 if (value) {
314                         newvariable = ast_var_assign(name, value);
315                         AST_LIST_INSERT_HEAD(headp, newvariable, entries);
316                 }
317         }
318
319         return 0;
320 }
321
322 int ast_cdr_copy_vars(struct ast_cdr *to_cdr, struct ast_cdr *from_cdr)
323 {
324         struct ast_var_t *variables, *newvariable = NULL;
325         struct varshead *headpa, *headpb;
326         const char *var, *val;
327         int x = 0;
328
329         headpa = &from_cdr->varshead;
330         headpb = &to_cdr->varshead;
331
332         AST_LIST_TRAVERSE(headpa,variables,entries) {
333                 if (variables &&
334                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
335                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
336                         newvariable = ast_var_assign(var, val);
337                         AST_LIST_INSERT_HEAD(headpb, newvariable, entries);
338                         x++;
339                 }
340         }
341
342         return x;
343 }
344
345 int ast_cdr_serialize_variables(struct ast_cdr *cdr, char *buf, size_t size, char delim, char sep, int recur) 
346 {
347         struct ast_var_t *variables;
348         const char *var, *val;
349         char *tmp;
350         char workspace[256];
351         int total = 0, x = 0, i;
352
353         memset(buf, 0, size);
354
355         for (; cdr; cdr = recur ? cdr->next : NULL) {
356                 if (++x > 1)
357                         ast_build_string(&buf, &size, "\n");
358
359                 AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
360                         if (variables &&
361                             (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
362                             !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
363                                 if (ast_build_string(&buf, &size, "level %d: %s%c%s%c", x, var, delim, val, sep)) {
364                                         ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
365                                         break;
366                                 } else
367                                         total++;
368                         } else 
369                                 break;
370                 }
371
372                 for (i = 0; cdr_readonly_vars[i]; i++) {
373                         ast_cdr_getvar(cdr, cdr_readonly_vars[i], &tmp, workspace, sizeof(workspace), 0, 0);
374                         if (!tmp)
375                                 continue;
376                         
377                         if (ast_build_string(&buf, &size, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, tmp, sep)) {
378                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
379                                 break;
380                         } else
381                                 total++;
382                 }
383         }
384
385         return total;
386 }
387
388
389 void ast_cdr_free_vars(struct ast_cdr *cdr, int recur)
390 {
391
392         /* clear variables */
393         for (; cdr; cdr = recur ? cdr->next : NULL) {
394                 struct ast_var_t *vardata;
395                 struct varshead *headp = &cdr->varshead;
396                 while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
397                         ast_var_delete(vardata);
398         }
399 }
400
401 /*! \brief  print a warning if cdr already posted */
402 static void check_post(struct ast_cdr *cdr)
403 {
404         if (ast_test_flag(cdr, AST_CDR_FLAG_POSTED))
405                 ast_log(LOG_WARNING, "CDR on channel '%s' already posted\n", S_OR(cdr->channel, "<unknown>"));
406 }
407
408 /*! \brief  print a warning if cdr already started */
409 static void check_start(struct ast_cdr *cdr)
410 {
411         if (!ast_tvzero(cdr->start))
412                 ast_log(LOG_WARNING, "CDR on channel '%s' already started\n", S_OR(cdr->channel, "<unknown>"));
413 }
414
415 void ast_cdr_free(struct ast_cdr *cdr)
416 {
417
418         while (cdr) {
419                 struct ast_cdr *next = cdr->next;
420                 char *chan = S_OR(cdr->channel, "<unknown>");
421                 if (!ast_test_flag(cdr, AST_CDR_FLAG_POSTED) && !ast_test_flag(cdr, AST_CDR_FLAG_POST_DISABLED))
422                         ast_log(LOG_WARNING, "CDR on channel '%s' not posted\n", chan);
423                 if (ast_tvzero(cdr->end))
424                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
425                 if (ast_tvzero(cdr->start))
426                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
427
428                 ast_cdr_free_vars(cdr, 0);
429                 free(cdr);
430                 cdr = next;
431         }
432 }
433
434 struct ast_cdr *ast_cdr_alloc(void)
435 {
436         return ast_calloc(1, sizeof(struct ast_cdr));
437 }
438
439 void ast_cdr_start(struct ast_cdr *cdr)
440 {
441         char *chan; 
442
443         for (; cdr; cdr = cdr->next) {
444                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
445                         chan = S_OR(cdr->channel, "<unknown>");
446                         check_post(cdr);
447                         check_start(cdr);
448                         cdr->start = ast_tvnow();
449                 }
450         }
451 }
452
453 void ast_cdr_answer(struct ast_cdr *cdr)
454 {
455
456         for (; cdr; cdr = cdr->next) {
457                 check_post(cdr);
458                 if (cdr->disposition < AST_CDR_ANSWERED)
459                         cdr->disposition = AST_CDR_ANSWERED;
460                 if (ast_tvzero(cdr->answer))
461                         cdr->answer = ast_tvnow();
462         }
463 }
464
465 void ast_cdr_busy(struct ast_cdr *cdr)
466 {
467
468         for (; cdr; cdr = cdr->next) {
469                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
470                         check_post(cdr);
471                         if (cdr->disposition < AST_CDR_BUSY)
472                                 cdr->disposition = AST_CDR_BUSY;
473                 }
474         }
475 }
476
477 void ast_cdr_failed(struct ast_cdr *cdr)
478 {
479         for (; cdr; cdr = cdr->next) {
480                 check_post(cdr);
481                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
482                         if (cdr->disposition < AST_CDR_FAILED)
483                                 cdr->disposition = AST_CDR_FAILED;
484                 }
485         }
486 }
487
488 int ast_cdr_disposition(struct ast_cdr *cdr, int cause)
489 {
490         int res = 0;
491
492         for (; cdr; cdr = cdr->next) {
493                 switch(cause) {
494                 case AST_CAUSE_BUSY:
495                         ast_cdr_busy(cdr);
496                         break;
497                 case AST_CAUSE_FAILURE:
498                         ast_cdr_failed(cdr);
499                         break;
500                 case AST_CAUSE_NORMAL:
501                         break;
502                 case AST_CAUSE_NOTDEFINED:
503                         res = -1;
504                         break;
505                 default:
506                         res = -1;
507                         ast_log(LOG_WARNING, "Cause not handled\n");
508                 }
509         }
510         return res;
511 }
512
513 void ast_cdr_setdestchan(struct ast_cdr *cdr, const char *chann)
514 {
515         for (; cdr; cdr = cdr->next) {
516                 check_post(cdr);
517                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
518                         ast_copy_string(cdr->dstchannel, chann, sizeof(cdr->dstchannel));
519         }
520 }
521
522 void ast_cdr_setapp(struct ast_cdr *cdr, char *app, char *data)
523 {
524
525         for (; cdr; cdr = cdr->next) {
526                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
527                         check_post(cdr);
528                         if (!app)
529                                 app = "";
530                         ast_copy_string(cdr->lastapp, app, sizeof(cdr->lastapp));
531                         if (!data)
532                                 data = "";
533                         ast_copy_string(cdr->lastdata, data, sizeof(cdr->lastdata));
534                 }
535         }
536 }
537
538 /* set cid info for one record */
539 static void set_one_cid(struct ast_cdr *cdr, struct ast_channel *c)
540 {
541         /* Grab source from ANI or normal Caller*ID */
542         const char *num = S_OR(c->cid.cid_ani, c->cid.cid_num);
543         
544         if (!ast_strlen_zero(c->cid.cid_name)) {
545                 if (!ast_strlen_zero(num))      /* both name and number */
546                         snprintf(cdr->clid, sizeof(cdr->clid), "\"%s\" <%s>", c->cid.cid_name, num);
547                 else                            /* only name */
548                         ast_copy_string(cdr->clid, c->cid.cid_name, sizeof(cdr->clid));
549         } else if (!ast_strlen_zero(num)) {     /* only number */
550                 ast_copy_string(cdr->clid, num, sizeof(cdr->clid));
551         } else {                                /* nothing known */
552                 cdr->clid[0] = '\0';
553         }
554         ast_copy_string(cdr->src, S_OR(num, ""), sizeof(cdr->src));
555
556 }
557 int ast_cdr_setcid(struct ast_cdr *cdr, struct ast_channel *c)
558 {
559         for (; cdr; cdr = cdr->next) {
560                 if (ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
561                         set_one_cid(cdr, c);
562         }
563         return 0;
564 }
565
566 int ast_cdr_init(struct ast_cdr *cdr, struct ast_channel *c)
567 {
568         char *chan;
569
570         for ( ; cdr ; cdr = cdr->next) {
571                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
572                         chan = S_OR(cdr->channel, "<unknown>");
573                         if (!ast_strlen_zero(cdr->channel)) 
574                                 ast_log(LOG_WARNING, "CDR already initialized on '%s'\n", chan); 
575                         ast_copy_string(cdr->channel, c->name, sizeof(cdr->channel));
576                         set_one_cid(cdr, c);
577
578                         cdr->disposition = (c->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NOANSWER;
579                         cdr->amaflags = c->amaflags ? c->amaflags :  ast_default_amaflags;
580                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
581                         /* Destination information */
582                         ast_copy_string(cdr->dst, c->exten, sizeof(cdr->dst));
583                         ast_copy_string(cdr->dcontext, c->context, sizeof(cdr->dcontext));
584                         /* Unique call identifier */
585                         ast_copy_string(cdr->uniqueid, c->uniqueid, sizeof(cdr->uniqueid));
586                 }
587         }
588         return 0;
589 }
590
591 void ast_cdr_end(struct ast_cdr *cdr)
592 {
593         for ( ; cdr ; cdr = cdr->next) {
594                 check_post(cdr);
595                 if (ast_tvzero(cdr->end))
596                         cdr->end = ast_tvnow();
597                 if (ast_tvzero(cdr->start)) {
598                         ast_log(LOG_WARNING, "CDR on channel '%s' has not started\n", S_OR(cdr->channel, "<unknown>"));
599                         cdr->disposition = AST_CDR_FAILED;
600                 } else
601                         cdr->duration = cdr->end.tv_sec - cdr->start.tv_sec;
602                 cdr->billsec = ast_tvzero(cdr->answer) ? 0 : cdr->end.tv_sec - cdr->answer.tv_sec;
603         }
604 }
605
606 char *ast_cdr_disp2str(int disposition)
607 {
608         switch (disposition) {
609         case AST_CDR_NOANSWER:
610                 return "NO ANSWER";
611         case AST_CDR_FAILED:
612                 return "FAILED";                
613         case AST_CDR_BUSY:
614                 return "BUSY";          
615         case AST_CDR_ANSWERED:
616                 return "ANSWERED";
617         }
618         return "UNKNOWN";
619 }
620
621 /*! Converts AMA flag to printable string */
622 char *ast_cdr_flags2str(int flag)
623 {
624         switch(flag) {
625         case AST_CDR_OMIT:
626                 return "OMIT";
627         case AST_CDR_BILLING:
628                 return "BILLING";
629         case AST_CDR_DOCUMENTATION:
630                 return "DOCUMENTATION";
631         }
632         return "Unknown";
633 }
634
635 int ast_cdr_setaccount(struct ast_channel *chan, const char *account)
636 {
637         struct ast_cdr *cdr = chan->cdr;
638
639         ast_string_field_set(chan, accountcode, account);
640         for ( ; cdr ; cdr = cdr->next) {
641                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
642                         ast_copy_string(cdr->accountcode, chan->accountcode, sizeof(cdr->accountcode));
643         }
644         return 0;
645 }
646
647 int ast_cdr_setamaflags(struct ast_channel *chan, const char *flag)
648 {
649         struct ast_cdr *cdr;
650         int newflag = ast_cdr_amaflags2int(flag);
651         if (newflag) {
652                 for (cdr = chan->cdr; cdr; cdr = cdr->next)
653                         cdr->amaflags = newflag;
654         }
655
656         return 0;
657 }
658
659 int ast_cdr_setuserfield(struct ast_channel *chan, const char *userfield)
660 {
661         struct ast_cdr *cdr = chan->cdr;
662
663         for ( ; cdr ; cdr = cdr->next) {
664                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) 
665                         ast_copy_string(cdr->userfield, userfield, sizeof(cdr->userfield));
666         }
667
668         return 0;
669 }
670
671 int ast_cdr_appenduserfield(struct ast_channel *chan, const char *userfield)
672 {
673         struct ast_cdr *cdr = chan->cdr;
674
675         for ( ; cdr ; cdr = cdr->next) {
676                 int len = strlen(cdr->userfield);
677
678                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED))
679                         strncpy(cdr->userfield+len, userfield, sizeof(cdr->userfield) - len - 1);
680         }
681
682         return 0;
683 }
684
685 int ast_cdr_update(struct ast_channel *c)
686 {
687         struct ast_cdr *cdr = c->cdr;
688
689         for ( ; cdr ; cdr = cdr->next) {
690                 if (!ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
691                         set_one_cid(cdr, c);
692
693                         /* Copy account code et-al */   
694                         ast_copy_string(cdr->accountcode, c->accountcode, sizeof(cdr->accountcode));
695                         /* Destination information */ /* XXX privilege macro* ? */
696                         ast_copy_string(cdr->dst, S_OR(c->macroexten, c->exten), sizeof(cdr->dst));
697                         ast_copy_string(cdr->dcontext, S_OR(c->macrocontext, c->context), sizeof(cdr->dcontext));
698                 }
699         }
700
701         return 0;
702 }
703
704 int ast_cdr_amaflags2int(const char *flag)
705 {
706         if (!strcasecmp(flag, "default"))
707                 return 0;
708         if (!strcasecmp(flag, "omit"))
709                 return AST_CDR_OMIT;
710         if (!strcasecmp(flag, "billing"))
711                 return AST_CDR_BILLING;
712         if (!strcasecmp(flag, "documentation"))
713                 return AST_CDR_DOCUMENTATION;
714         return -1;
715 }
716
717 static void post_cdr(struct ast_cdr *cdr)
718 {
719         char *chan;
720         struct ast_cdr_beitem *i;
721
722         for ( ; cdr ; cdr = cdr->next) {
723                 chan = S_OR(cdr->channel, "<unknown>");
724                 check_post(cdr);
725                 if (ast_tvzero(cdr->end))
726                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks end\n", chan);
727                 if (ast_tvzero(cdr->start))
728                         ast_log(LOG_WARNING, "CDR on channel '%s' lacks start\n", chan);
729                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
730                 AST_LIST_LOCK(&be_list);
731                 AST_LIST_TRAVERSE(&be_list, i, list) {
732                         i->be(cdr);
733                 }
734                 AST_LIST_UNLOCK(&be_list);
735         }
736 }
737
738 void ast_cdr_reset(struct ast_cdr *cdr, struct ast_flags *_flags)
739 {
740         struct ast_cdr *dup;
741         struct ast_flags flags = { 0 };
742
743         if (_flags)
744                 ast_copy_flags(&flags, _flags, AST_FLAGS_ALL);
745
746         for ( ; cdr ; cdr = cdr->next) {
747                 /* Detach if post is requested */
748                 if (ast_test_flag(&flags, AST_CDR_FLAG_LOCKED) || !ast_test_flag(cdr, AST_CDR_FLAG_LOCKED)) {
749                         if (ast_test_flag(&flags, AST_CDR_FLAG_POSTED)) {
750                                 ast_cdr_end(cdr);
751                                 if ((dup = ast_cdr_dup(cdr))) {
752                                         ast_cdr_detach(dup);
753                                 }
754                                 ast_set_flag(cdr, AST_CDR_FLAG_POSTED);
755                         }
756
757                         /* clear variables */
758                         if (!ast_test_flag(&flags, AST_CDR_FLAG_KEEP_VARS)) {
759                                 ast_cdr_free_vars(cdr, 0);
760                         }
761
762                         /* Reset to initial state */
763                         ast_clear_flag(cdr, AST_FLAGS_ALL);     
764                         memset(&cdr->start, 0, sizeof(cdr->start));
765                         memset(&cdr->end, 0, sizeof(cdr->end));
766                         memset(&cdr->answer, 0, sizeof(cdr->answer));
767                         cdr->billsec = 0;
768                         cdr->duration = 0;
769                         ast_cdr_start(cdr);
770                         cdr->disposition = AST_CDR_NOANSWER;
771                 }
772         }
773 }
774
775 struct ast_cdr *ast_cdr_append(struct ast_cdr *cdr, struct ast_cdr *newcdr) 
776 {
777         struct ast_cdr *ret;
778
779         if (cdr) {
780                 ret = cdr;
781
782                 while (cdr->next)
783                         cdr = cdr->next;
784                 cdr->next = newcdr;
785         } else {
786                 ret = newcdr;
787         }
788
789         return ret;
790 }
791
792 /*! \note Don't call without cdr_batch_lock */
793 static void reset_batch(void)
794 {
795         batch->size = 0;
796         batch->head = NULL;
797         batch->tail = NULL;
798 }
799
800 /*! \note Don't call without cdr_batch_lock */
801 static int init_batch(void)
802 {
803         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
804         if (!(batch = ast_malloc(sizeof(*batch))))
805                 return -1;
806
807         reset_batch();
808
809         return 0;
810 }
811
812 static void *do_batch_backend_process(void *data)
813 {
814         struct ast_cdr_batch_item *processeditem;
815         struct ast_cdr_batch_item *batchitem = data;
816
817         /* Push each CDR into storage mechanism(s) and free all the memory */
818         while (batchitem) {
819                 post_cdr(batchitem->cdr);
820                 ast_cdr_free(batchitem->cdr);
821                 processeditem = batchitem;
822                 batchitem = batchitem->next;
823                 free(processeditem);
824         }
825
826         return NULL;
827 }
828
829 void ast_cdr_submit_batch(int shutdown)
830 {
831         struct ast_cdr_batch_item *oldbatchitems = NULL;
832         pthread_attr_t attr;
833         pthread_t batch_post_thread = AST_PTHREADT_NULL;
834
835         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
836         if (!batch || !batch->head)
837                 return;
838
839         /* move the old CDRs aside, and prepare a new CDR batch */
840         ast_mutex_lock(&cdr_batch_lock);
841         oldbatchitems = batch->head;
842         reset_batch();
843         ast_mutex_unlock(&cdr_batch_lock);
844
845         /* if configured, spawn a new thread to post these CDRs,
846            also try to save as much as possible if we are shutting down safely */
847         if (batchscheduleronly || shutdown) {
848                 if (option_debug)
849                         ast_log(LOG_DEBUG, "CDR single-threaded batch processing begins now\n");
850                 do_batch_backend_process(oldbatchitems);
851         } else {
852                 pthread_attr_init(&attr);
853                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
854                 if (ast_pthread_create(&batch_post_thread, &attr, do_batch_backend_process, oldbatchitems)) {
855                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
856                         do_batch_backend_process(oldbatchitems);
857                 } else {
858                         if (option_debug)
859                                 ast_log(LOG_DEBUG, "CDR multi-threaded batch processing begins now\n");
860                 }
861         }
862 }
863
864 static int submit_scheduled_batch(void *data)
865 {
866         ast_cdr_submit_batch(0);
867         /* manually reschedule from this point in time */
868         cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
869         /* returning zero so the scheduler does not automatically reschedule */
870         return 0;
871 }
872
873 static void submit_unscheduled_batch(void)
874 {
875         /* this is okay since we are not being called from within the scheduler */
876         if (cdr_sched > -1)
877                 ast_sched_del(sched, cdr_sched);
878         /* schedule the submission to occur ASAP (1 ms) */
879         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
880         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
881         ast_mutex_lock(&cdr_pending_lock);
882         ast_cond_signal(&cdr_pending_cond);
883         ast_mutex_unlock(&cdr_pending_lock);
884 }
885
886 void ast_cdr_detach(struct ast_cdr *cdr)
887 {
888         struct ast_cdr_batch_item *newtail;
889         int curr;
890
891         /* maybe they disabled CDR stuff completely, so just drop it */
892         if (!enabled) {
893                 if (option_debug)
894                         ast_log(LOG_DEBUG, "Dropping CDR !\n");
895                 ast_set_flag(cdr, AST_CDR_FLAG_POST_DISABLED);
896                 ast_cdr_free(cdr);
897                 return;
898         }
899
900         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
901         if (!batchmode) {
902                 post_cdr(cdr);
903                 ast_cdr_free(cdr);
904                 return;
905         }
906
907         /* otherwise, each CDR gets put into a batch list (at the end) */
908         if (option_debug)
909                 ast_log(LOG_DEBUG, "CDR detaching from this thread\n");
910
911         /* we'll need a new tail for every CDR */
912         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
913                 post_cdr(cdr);
914                 ast_cdr_free(cdr);
915                 return;
916         }
917
918         /* don't traverse a whole list (just keep track of the tail) */
919         ast_mutex_lock(&cdr_batch_lock);
920         if (!batch)
921                 init_batch();
922         if (!batch->head) {
923                 /* new batch is empty, so point the head at the new tail */
924                 batch->head = newtail;
925         } else {
926                 /* already got a batch with something in it, so just append a new tail */
927                 batch->tail->next = newtail;
928         }
929         newtail->cdr = cdr;
930         batch->tail = newtail;
931         curr = batch->size++;
932         ast_mutex_unlock(&cdr_batch_lock);
933
934         /* if we have enough stuff to post, then do it */
935         if (curr >= (batchsize - 1))
936                 submit_unscheduled_batch();
937 }
938
939 static void *do_cdr(void *data)
940 {
941         struct timespec timeout;
942         int schedms;
943         int numevents = 0;
944
945         for(;;) {
946                 struct timeval now = ast_tvnow();
947                 schedms = ast_sched_wait(sched);
948                 /* this shouldn't happen, but provide a 1 second default just in case */
949                 if (schedms <= 0)
950                         schedms = 1000;
951                 timeout.tv_sec = now.tv_sec + (schedms / 1000);
952                 timeout.tv_nsec = (now.tv_usec * 1000) + ((schedms % 1000) * 1000);
953                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
954                 ast_mutex_lock(&cdr_pending_lock);
955                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
956                 numevents = ast_sched_runq(sched);
957                 ast_mutex_unlock(&cdr_pending_lock);
958                 if (option_debug > 1)
959                         ast_log(LOG_DEBUG, "Processed %d scheduled CDR batches from the run queue\n", numevents);
960         }
961
962         return NULL;
963 }
964
965 static int handle_cli_status(int fd, int argc, char *argv[])
966 {
967         struct ast_cdr_beitem *beitem=NULL;
968         int cnt=0;
969         long nextbatchtime=0;
970
971         if (argc > 2)
972                 return RESULT_SHOWUSAGE;
973
974         ast_cli(fd, "CDR logging: %s\n", enabled ? "enabled" : "disabled");
975         ast_cli(fd, "CDR mode: %s\n", batchmode ? "batch" : "simple");
976         if (enabled) {
977                 if (batchmode) {
978                         if (batch)
979                                 cnt = batch->size;
980                         if (cdr_sched > -1)
981                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
982                         ast_cli(fd, "CDR safe shut down: %s\n", batchsafeshutdown ? "enabled" : "disabled");
983                         ast_cli(fd, "CDR batch threading model: %s\n", batchscheduleronly ? "scheduler only" : "scheduler plus separate threads");
984                         ast_cli(fd, "CDR current batch size: %d record%s\n", cnt, (cnt != 1) ? "s" : "");
985                         ast_cli(fd, "CDR maximum batch size: %d record%s\n", batchsize, (batchsize != 1) ? "s" : "");
986                         ast_cli(fd, "CDR maximum batch time: %d second%s\n", batchtime, (batchtime != 1) ? "s" : "");
987                         ast_cli(fd, "CDR next scheduled batch processing time: %ld second%s\n", nextbatchtime, (nextbatchtime != 1) ? "s" : "");
988                 }
989                 AST_LIST_LOCK(&be_list);
990                 AST_LIST_TRAVERSE(&be_list, beitem, list) {
991                         ast_cli(fd, "CDR registered backend: %s\n", beitem->name);
992                 }
993                 AST_LIST_UNLOCK(&be_list);
994         }
995
996         return 0;
997 }
998
999 static int handle_cli_submit(int fd, int argc, char *argv[])
1000 {
1001         if (argc > 2)
1002                 return RESULT_SHOWUSAGE;
1003
1004         submit_unscheduled_batch();
1005         ast_cli(fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
1006
1007         return 0;
1008 }
1009
1010 static struct ast_cli_entry cli_submit = {
1011         .cmda = { "cdr", "submit", NULL },
1012         .handler = handle_cli_submit,
1013         .summary = "Posts all pending batched CDR data",
1014         .usage =
1015         "Usage: cdr submit\n"
1016         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n"
1017 };
1018
1019 static struct ast_cli_entry cli_status = {
1020         .cmda = { "cdr", "status", NULL },
1021         .handler = handle_cli_status,
1022         .summary = "Display the CDR status",
1023         .usage =
1024         "Usage: cdr status\n"
1025         "       Displays the Call Detail Record engine system status.\n"
1026 };
1027
1028 static int do_reload(void)
1029 {
1030         struct ast_config *config;
1031         const char *enabled_value;
1032         const char *batched_value;
1033         const char *scheduleronly_value;
1034         const char *batchsafeshutdown_value;
1035         const char *size_value;
1036         const char *time_value;
1037         const char *end_before_h_value;
1038         int cfg_size;
1039         int cfg_time;
1040         int was_enabled;
1041         int was_batchmode;
1042         int res=0;
1043
1044         ast_mutex_lock(&cdr_batch_lock);
1045
1046         batchsize = BATCH_SIZE_DEFAULT;
1047         batchtime = BATCH_TIME_DEFAULT;
1048         batchscheduleronly = BATCH_SCHEDULER_ONLY_DEFAULT;
1049         batchsafeshutdown = BATCH_SAFE_SHUTDOWN_DEFAULT;
1050         was_enabled = enabled;
1051         was_batchmode = batchmode;
1052         enabled = 1;
1053         batchmode = 0;
1054
1055         /* don't run the next scheduled CDR posting while reloading */
1056         if (cdr_sched > -1)
1057                 ast_sched_del(sched, cdr_sched);
1058
1059         if ((config = ast_config_load("cdr.conf"))) {
1060                 if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
1061                         enabled = ast_true(enabled_value);
1062                 }
1063                 if ((batched_value = ast_variable_retrieve(config, "general", "batch"))) {
1064                         batchmode = ast_true(batched_value);
1065                 }
1066                 if ((scheduleronly_value = ast_variable_retrieve(config, "general", "scheduleronly"))) {
1067                         batchscheduleronly = ast_true(scheduleronly_value);
1068                 }
1069                 if ((batchsafeshutdown_value = ast_variable_retrieve(config, "general", "safeshutdown"))) {
1070                         batchsafeshutdown = ast_true(batchsafeshutdown_value);
1071                 }
1072                 if ((size_value = ast_variable_retrieve(config, "general", "size"))) {
1073                         if (sscanf(size_value, "%d", &cfg_size) < 1)
1074                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", size_value);
1075                         else if (size_value < 0)
1076                                 ast_log(LOG_WARNING, "Invalid maximum batch size '%d' specified, using default\n", cfg_size);
1077                         else
1078                                 batchsize = cfg_size;
1079                 }
1080                 if ((time_value = ast_variable_retrieve(config, "general", "time"))) {
1081                         if (sscanf(time_value, "%d", &cfg_time) < 1)
1082                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", time_value);
1083                         else if (time_value < 0)
1084                                 ast_log(LOG_WARNING, "Invalid maximum batch time '%d' specified, using default\n", cfg_time);
1085                         else
1086                                 batchtime = cfg_time;
1087                 }
1088                 if ((end_before_h_value = ast_variable_retrieve(config, "general", "endbeforehexten")))
1089                         ast_set2_flag(&ast_options, ast_true(end_before_h_value), AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN);
1090         }
1091
1092         if (enabled && !batchmode) {
1093                 ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
1094         } else if (enabled && batchmode) {
1095                 cdr_sched = ast_sched_add(sched, batchtime * 1000, submit_scheduled_batch, NULL);
1096                 ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n", batchsize, batchtime);
1097         } else {
1098                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
1099         }
1100
1101         /* if this reload enabled the CDR batch mode, create the background thread
1102            if it does not exist */
1103         if (enabled && batchmode && (!was_enabled || !was_batchmode) && (cdr_thread == AST_PTHREADT_NULL)) {
1104                 ast_cond_init(&cdr_pending_cond, NULL);
1105                 if (ast_pthread_create(&cdr_thread, NULL, do_cdr, NULL) < 0) {
1106                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
1107                         ast_sched_del(sched, cdr_sched);
1108                 } else {
1109                         ast_cli_register(&cli_submit);
1110                         ast_register_atexit(ast_cdr_engine_term);
1111                         res = 0;
1112                 }
1113         /* if this reload disabled the CDR and/or batch mode and there is a background thread,
1114            kill it */
1115         } else if (((!enabled && was_enabled) || (!batchmode && was_batchmode)) && (cdr_thread != AST_PTHREADT_NULL)) {
1116                 /* wake up the thread so it will exit */
1117                 pthread_cancel(cdr_thread);
1118                 pthread_kill(cdr_thread, SIGURG);
1119                 pthread_join(cdr_thread, NULL);
1120                 cdr_thread = AST_PTHREADT_NULL;
1121                 ast_cond_destroy(&cdr_pending_cond);
1122                 ast_cli_unregister(&cli_submit);
1123                 ast_unregister_atexit(ast_cdr_engine_term);
1124                 res = 0;
1125                 /* if leaving batch mode, then post the CDRs in the batch,
1126                    and don't reschedule, since we are stopping CDR logging */
1127                 if (!batchmode && was_batchmode) {
1128                         ast_cdr_engine_term();
1129                 }
1130         } else {
1131                 res = 0;
1132         }
1133
1134         ast_mutex_unlock(&cdr_batch_lock);
1135         ast_config_destroy(config);
1136
1137         return res;
1138 }
1139
1140 int ast_cdr_engine_init(void)
1141 {
1142         int res;
1143
1144         sched = sched_context_create();
1145         if (!sched) {
1146                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
1147                 return -1;
1148         }
1149
1150         ast_cli_register(&cli_status);
1151
1152         res = do_reload();
1153         if (res) {
1154                 ast_mutex_lock(&cdr_batch_lock);
1155                 res = init_batch();
1156                 ast_mutex_unlock(&cdr_batch_lock);
1157         }
1158
1159         return res;
1160 }
1161
1162 /* \note This actually gets called a couple of times at shutdown.  Once, before we start
1163    hanging up channels, and then again, after the channel hangup timeout expires */
1164 void ast_cdr_engine_term(void)
1165 {
1166         ast_cdr_submit_batch(batchsafeshutdown);
1167 }
1168
1169 int ast_cdr_engine_reload(void)
1170 {
1171         return do_reload();
1172 }
1173