Update Asterisk's CDRs for the new bridging framework
[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 /*! \li \ref cdr.c uses the configuration file \ref cdr.conf
34  * \addtogroup configuration_file Configuration Files
35  */
36
37 /*!
38  * \page cdr.conf cdr.conf
39  * \verbinclude cdr.conf.sample
40  */
41
42 /*** MODULEINFO
43         <support_level>core</support_level>
44  ***/
45
46 #include "asterisk.h"
47
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
49
50 #include <signal.h>
51 #include <inttypes.h>
52
53 #include "asterisk/lock.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/cdr.h"
56 #include "asterisk/callerid.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/utils.h"
61 #include "asterisk/sched.h"
62 #include "asterisk/config.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/stringfields.h"
65 #include "asterisk/data.h"
66 #include "asterisk/config_options.h"
67 #include "asterisk/json.h"
68 #include "asterisk/stasis.h"
69 #include "asterisk/stasis_channels.h"
70 #include "asterisk/stasis_bridging.h"
71 #include "asterisk/stasis_message_router.h"
72 #include "asterisk/astobj2.h"
73
74 /*** DOCUMENTATION
75         <configInfo name="cdr" language="en_US">
76                 <synopsis>Call Detail Record configuration</synopsis>
77                 <description>
78                         <para>CDR is Call Detail Record, which provides logging services via a variety of
79                         pluggable backend modules. Detailed call information can be recorded to
80                         databases, files, etc. Useful for billing, fraud prevention, compliance with
81                         Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
82                 </description>
83                 <configFile name="cdr.conf">
84                         <configObject name="general">
85                                 <synopsis>Global settings applied to the CDR engine.</synopsis>
86                                 <configOption name="debug">
87                                         <synopsis>Enable/disable verbose CDR debugging.</synopsis>
88                                         <description><para>When set to <literal>True</literal>, verbose updates
89                                         of changes in CDR information will be logged. Note that this is only
90                                         of use when debugging CDR behavior.</para>
91                                         </description>
92                                 </configOption>
93                                 <configOption name="enable">
94                                         <synopsis>Enable/disable CDR logging.</synopsis>
95                                         <description><para>Define whether or not to use CDR logging. Setting this to "no" will override
96                                         any loading of backend CDR modules.  Default is "yes".</para>
97                                         </description>
98                                 </configOption>
99                                 <configOption name="unanswered">
100                                         <synopsis>Log calls that are never answered.</synopsis>
101                                         <description><para>Define whether or not to log unanswered calls. Setting this to "yes" will
102                                         report every attempt to ring a phone in dialing attempts, when it was not
103                                         answered. For example, if you try to dial 3 extensions, and this option is "yes",
104                                         you will get 3 CDR's, one for each phone that was rung. Some find this information horribly
105                                         useless. Others find it very valuable. Note, in "yes" mode, you will see one CDR, with one of
106                                         the call targets on one side, and the originating channel on the other, and then one CDR for
107                                         each channel attempted. This may seem redundant, but cannot be helped.</para>
108                                         <para>In brief, this option controls the reporting of unanswered calls which only have an A
109                                         party. Calls which get offered to an outgoing line, but are unanswered, are still
110                                         logged, and that is the intended behavior. (It also results in some B side CDRs being
111                                         output, as they have the B side channel as their source channel, and no destination
112                                         channel.)</para>
113                                         </description>
114                                 </configOption>
115                                 <configOption name="congestion">
116                                         <synopsis>Log congested calls.</synopsis>
117                                         <description><para>Define whether or not to log congested calls. Setting this to "yes" will
118                                         report each call that fails to complete due to congestion conditions.</para>
119                                         </description>
120                                 </configOption>
121                                 <configOption name="endbeforehexten">
122                                         <synopsis>End the CDR before executing the "h" extension</synopsis>
123                                         <description><para>Normally, CDR's are not closed out until after all extensions are finished
124                                         executing.  By enabling this option, the CDR will be ended before executing
125                                         the <literal>h</literal> extension and hangup handlers so that CDR values such as <literal>end</literal> and
126                                         <literal>"billsec"</literal> may be retrieved inside of this extension.
127                                         The default value is "no".</para>
128                                         </description>
129                                 </configOption>
130                                 <configOption name="initiatedseconds">
131                                         <synopsis>Count microseconds for billsec purposes</synopsis>
132                                         <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
133                                         is simply the end time (hangup time) minus the answer time in seconds. Internally,
134                                         asterisk stores the time in terms of microseconds and seconds. By setting
135                                         initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
136                                         that were initiated (a sort of round up method). Technically, this is
137                                         when the microsecond part of the end time is greater than the microsecond
138                                         part of the answer time, then the billsec time is incremented one second.</para>
139                                         </description>
140                                 </configOption>
141                                 <configOption name="batch">
142                                         <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
143                                         <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
144                                         every call, the data will be stored in a buffer to help alleviate load on the
145                                         asterisk server.</para>
146                                         <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
147                                         i.e., software crash, power failure, kill -9, etc.</para>
148                                         </warning>
149                                         </description>
150                                 </configOption>
151                                 <configOption name="size">
152                                         <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
153                                         <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
154                                         them to the backend engines. batch must be set to <literal>yes</literal>.</para>
155                                         </description>
156                                 </configOption>
157                                 <configOption name="time">
158                                         <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
159                                         <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
160                                         backend engines. If this time limit is reached, then it will post the records, regardless of the value
161                                         defined for size. batch must be set to <literal>yes</literal>.</para>
162                                         <note><para>Time is expressed in seconds.</para></note>
163                                         </description>
164                                 </configOption>
165                                 <configOption name="scheduleronly">
166                                         <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
167                                         <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
168                                         records.  Posting can either occur inside the scheduler thread, or a new
169                                         thread can be spawned for the submission of every batch.  For small batches,
170                                         it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
171                                         For large batches, say anything over size=10, a new thread is recommended, so
172                                         set this to <literal>no</literal>.</para>
173                                         </description>
174                                 </configOption>
175                                 <configOption name="safeshutdown">
176                                         <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
177                                         <description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
178                                         you don't, then data will likely be lost.  You can always check the size of
179                                         the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
180                                         submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
181                                         </description>
182                                 </configOption>
183                         </configObject>
184                 </configFile>
185         </configInfo>
186  ***/
187
188
189 #define DEFAULT_ENABLED "1"
190 #define DEFAULT_BATCHMODE "0"
191 #define DEFAULT_UNANSWERED "0"
192 #define DEFAULT_CONGESTION "0"
193 #define DEFAULT_END_BEFORE_H_EXTEN "0"
194 #define DEFAULT_INITIATED_SECONDS "0"
195
196 #define DEFAULT_BATCH_SIZE "100"
197 #define MAX_BATCH_SIZE 1000
198 #define DEFAULT_BATCH_TIME "300"
199 #define MAX_BATCH_TIME 86400
200 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
201 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
202
203 #define CDR_DEBUG(mod_cfg, fmt, ...) \
204         do { \
205         if (ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG)) { \
206                 ast_verb(1, (fmt), ##__VA_ARGS__); \
207         } } while (0)
208
209 static void cdr_detach(struct ast_cdr *cdr);
210 static void cdr_submit_batch(int shutdown);
211
212 /*! \brief The configuration settings for this module */
213 struct module_config {
214         struct ast_cdr_config *general;         /*< CDR global settings */
215 };
216
217 /*! \brief The container for the module configuration */
218 static AO2_GLOBAL_OBJ_STATIC(module_configs);
219
220 /*! \brief The type definition for general options */
221 static struct aco_type general_option = {
222         .type = ACO_GLOBAL,
223         .name = "general",
224         .item_offset = offsetof(struct module_config, general),
225         .category = "^general$",
226         .category_match = ACO_WHITELIST,
227 };
228
229 static void *module_config_alloc(void);
230 static void module_config_destructor(void *obj);
231
232 /*! \brief The file definition */
233 static struct aco_file module_file_conf = {
234         .filename = "cdr.conf",
235         .skip_category = "(^csv$|^custom$|^manager$|^odbc$|^pgsql$|^radius$|^sqlite$|^tds$|^mysql$)",
236         .types = ACO_TYPES(&general_option),
237 };
238
239 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
240         .files = ACO_FILES(&module_file_conf),
241 );
242
243 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
244
245 /*! \brief Dispose of a module config object */
246 static void module_config_destructor(void *obj)
247 {
248         struct module_config *cfg = obj;
249
250         if (!cfg) {
251                 return;
252         }
253         ao2_ref(cfg->general, -1);
254 }
255
256 /*! \brief Create a new module config object */
257 static void *module_config_alloc(void)
258 {
259         struct module_config *mod_cfg;
260         struct ast_cdr_config *cdr_config;
261
262         mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
263         if (!mod_cfg) {
264                 return NULL;
265         }
266
267         cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
268         if (!cdr_config) {
269                 ao2_ref(cdr_config, -1);
270                 return NULL;
271         }
272         mod_cfg->general = cdr_config;
273
274         return mod_cfg;
275 }
276
277 /*! \brief Registration object for CDR backends */
278 struct cdr_beitem {
279         char name[20];
280         char desc[80];
281         ast_cdrbe be;
282         AST_RWLIST_ENTRY(cdr_beitem) list;
283 };
284
285 /*! \brief List of registered backends */
286 static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
287
288 /*! \brief Queued CDR waiting to be batched */
289 struct cdr_batch_item {
290         struct ast_cdr *cdr;
291         struct cdr_batch_item *next;
292 };
293
294 /*! \brief The actual batch queue */
295 static struct cdr_batch {
296         int size;
297         struct cdr_batch_item *head;
298         struct cdr_batch_item *tail;
299 } *batch = NULL;
300
301 /*! \brief The global sequence counter used for CDRs */
302 static int global_cdr_sequence =  0;
303
304 /*! \brief Scheduler items */
305 static struct ast_sched_context *sched;
306 static int cdr_sched = -1;
307 AST_MUTEX_DEFINE_STATIC(cdr_sched_lock);
308 static pthread_t cdr_thread = AST_PTHREADT_NULL;
309
310 /*! \brief Lock protecting modifications to the batch queue */
311 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
312
313 /*! \brief These are used to wake up the CDR thread when there's work to do */
314 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
315 static ast_cond_t cdr_pending_cond;
316
317 /*! \brief A container of the active CDRs indexed by Party A channel name */
318 static struct ao2_container *active_cdrs_by_channel;
319
320 /*! \brief A container of the active CDRs indexed by the bridge ID */
321 static struct ao2_container *active_cdrs_by_bridge;
322
323 /*! \brief Message router for stasis messages regarding channel state */
324 static struct stasis_message_router *stasis_router;
325
326 /*! \brief Our subscription for bridges */
327 static struct stasis_subscription *bridge_subscription;
328
329 /*! \brief Our subscription for channels */
330 static struct stasis_subscription *channel_subscription;
331
332 /*! \brief The parent topic for all topics we want to aggregate for CDRs */
333 static struct stasis_topic *cdr_topic;
334
335 struct cdr_object;
336
337 /*!
338  * \brief A virtual table used for \ref cdr_object.
339  *
340  * Note that all functions are optional - if a subclass does not need an
341  * implementation, it is safe to leave it NULL.
342  */
343 struct cdr_object_fn_table {
344         /*! \brief Name of the subclass */
345         const char *name;
346
347         /*!
348          * \brief An initialization function. This will be called automatically
349          * when a \ref cdr_object is switched to this type in
350          * \ref cdr_object_transition_state
351          *
352          * \param cdr The \ref cdr_object that was just transitioned
353          */
354         void (* const init_function)(struct cdr_object *cdr);
355
356         /*!
357          * \brief Process a Party A update for the \ref cdr_object
358          *
359          * \param cdr The \ref cdr_object to process the update
360          * \param snapshot The snapshot for the CDR's Party A
361          * \retval 0 the CDR handled the update or ignored it
362          * \retval 1 the CDR is finalized and a new one should be made to handle it
363          */
364         int (* const process_party_a)(struct cdr_object *cdr,
365                         struct ast_channel_snapshot *snapshot);
366
367         /*!
368          * \brief Process a Party B update for the \ref cdr_object
369          *
370          * \param cdr The \ref cdr_object to process the update
371          * \param snapshot The snapshot for the CDR's Party B
372          */
373         void (* const process_party_b)(struct cdr_object *cdr,
374                         struct ast_channel_snapshot *snapshot);
375
376         /*!
377          * \brief Process the beginning of a dial. A dial message implies one of two
378          * things:
379          * The \ref cdr_object's Party A has been originated
380          * The \ref cdr_object's Party A is dialing its Party B
381          *
382          * \param cdr The \ref cdr_object
383          * \param caller The originator of the dial attempt
384          * \param peer The destination of the dial attempt
385          *
386          * \retval 0 if the parties in the dial were handled by this CDR
387          * \retval 1 if the parties could not be handled by this CDR
388          */
389         int (* const process_dial_begin)(struct cdr_object *cdr,
390                         struct ast_channel_snapshot *caller,
391                         struct ast_channel_snapshot *peer);
392
393         /*!
394          * \brief Process the end of a dial. At the end of a dial, a CDR can be
395          * transitioned into one of two states - DialedPending
396          * (\ref dialed_pending_state_fn_table) or Finalized
397          * (\ref finalized_state_fn_table).
398          *
399          * \param cdr The \ref cdr_object
400          * \param caller The originator of the dial attempt
401          * \param peer the Destination of the dial attempt
402          * \param dial_status What happened
403          *
404          * \retval 0 if the parties in the dial were handled by this CDR
405          * \retval 1 if the parties could not be handled by this CDR
406          */
407         int (* const process_dial_end)(struct cdr_object *cdr,
408                         struct ast_channel_snapshot *caller,
409                         struct ast_channel_snapshot *peer,
410                         const char *dial_status);
411
412         /*!
413          * \brief Process the entering of a bridge by this CDR. The purpose of this
414          * callback is to have the CDR prepare itself for the bridge and attempt to
415          * find a valid Party B. The act of creating new CDRs based on the entering
416          * of this channel into the bridge is handled by the higher level message
417          * handler.
418          *
419          * \param cdr The \ref cdr_object
420          * \param bridge The bridge that the Party A just entered into
421          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
422          *
423          * \retval 0 This CDR found a Party B for itself and updated it, or there
424          * was no Party B to find (we're all alone)
425          * \retval 1 This CDR couldn't find a Party B, and there were options
426          */
427         int (* const process_bridge_enter)(struct cdr_object *cdr,
428                         struct ast_bridge_snapshot *bridge,
429                         struct ast_channel_snapshot *channel);
430
431         /*!
432          * \brief Process the leaving of a bridge by this CDR.
433          *
434          * \param cdr The \ref cdr_object
435          * \param bridge The bridge that the Party A just left
436          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
437          *
438          * \retval 0 This CDR left successfully
439          * \retval 1 Error
440          */
441         int (* const process_bridge_leave)(struct cdr_object *cdr,
442                         struct ast_bridge_snapshot *bridge,
443                         struct ast_channel_snapshot *channel);
444 };
445
446 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
447 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
448 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
449
450 static void single_state_init_function(struct cdr_object *cdr);
451 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
452 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
453 static int single_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
454
455 /*!
456  * \brief The virtual table for the Single state.
457  *
458  * A \ref cdr_object starts off in this state. This represents a channel that
459  * has no Party B information itself.
460  *
461  * A \ref cdr_object from this state can go into any of the following states:
462  * * \ref dial_state_fn_table
463  * * \ref bridge_state_fn_table
464  * * \ref finalized_state_fn_table
465  */
466 struct cdr_object_fn_table single_state_fn_table = {
467         .name = "Single",
468         .init_function = single_state_init_function,
469         .process_party_a = base_process_party_a,
470         .process_party_b = single_state_process_party_b,
471         .process_dial_begin = single_state_process_dial_begin,
472         .process_dial_end = base_process_dial_end,
473         .process_bridge_enter = single_state_process_bridge_enter,
474         .process_bridge_leave = base_process_bridge_leave,
475 };
476
477 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
478 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
479 static int dial_state_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
480 static int dial_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
481
482 /*!
483  * \brief The virtual table for the Dial state.
484  *
485  * A \ref cdr_object that has begun a dial operation. This state is entered when
486  * the Party A for a CDR is determined to be dialing out to a Party B or when
487  * a CDR is for an originated channel (in which case the Party A information is
488  * the originated channel, and there is no Party B).
489  *
490  * A \ref cdr_object from this state can go in any of the following states:
491  * * \ref dialed_pending_state_fn_table
492  * * \ref bridge_state_fn_table
493  * * \ref finalized_state_fn_table
494  */
495 struct cdr_object_fn_table dial_state_fn_table = {
496         .name = "Dial",
497         .process_party_a = base_process_party_a,
498         .process_party_b = dial_state_process_party_b,
499         .process_dial_begin = dial_state_process_dial_begin,
500         .process_dial_end = dial_state_process_dial_end,
501         .process_bridge_enter = dial_state_process_bridge_enter,
502         .process_bridge_leave = base_process_bridge_leave,
503 };
504
505 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
506 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
507 static int dialed_pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
508
509 /*!
510  * \brief The virtual table for the Dialed Pending state.
511  *
512  * A \ref cdr_object that has successfully finished a dial operation, but we
513  * don't know what they're going to do yet. It's theoretically possible to dial
514  * a party and then have that party not be bridged with the caller; likewise,
515  * an origination can complete and the channel go off and execute dialplan. The
516  * pending state acts as a bridge between either:
517  * * Entering a bridge
518  * * Getting a new CDR for new dialplan execution
519  * * Switching from being originated to executing dialplan
520  *
521  * A \ref cdr_object from this state can go in any of the following states:
522  * * \ref single_state_fn_table
523  * * \ref dialed_pending_state_fn_table
524  * * \ref bridge_state_fn_table
525  * * \ref finalized_state_fn_table
526  */
527 struct cdr_object_fn_table dialed_pending_state_fn_table = {
528         .name = "DialedPending",
529         .process_party_a = dialed_pending_state_process_party_a,
530         .process_dial_begin = dialed_pending_state_process_dial_begin,
531         .process_bridge_enter = dialed_pending_state_process_bridge_enter,
532         .process_bridge_leave = base_process_bridge_leave,
533 };
534
535 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
536 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
537
538 /*!
539  * \brief The virtual table for the Bridged state
540  *
541  * A \ref cdr_object enters this state when it receives notification that the
542  * channel has entered a bridge.
543  *
544  * A \ref cdr_object from this state can go to:
545  * * \ref finalized_state_fn_table
546  * * \ref pending_state_fn_table
547  */
548 struct cdr_object_fn_table bridge_state_fn_table = {
549         .name = "Bridged",
550         .process_party_a = base_process_party_a,
551         .process_party_b = bridge_state_process_party_b,
552         .process_bridge_leave = bridge_state_process_bridge_leave,
553 };
554
555 static void pending_state_init_function(struct cdr_object *cdr);
556 static int pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
557 static int pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
558 static int pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
559
560 /*!
561  * \brief The virtual table for the Pending state
562  *
563  * At certain times, we don't know where to go with the CDR. A good example is
564  * when a channel leaves a bridge - we don't know if the channel is about to
565  * be hung up; if it is about to go execute dialplan; dial someone; go into
566  * another bridge, etc. At these times, the CDR goes into pending and observes
567  * the messages that come in next to infer where the next logical place to go
568  * is.
569  *
570  * In this state, a CDR can go anywhere!
571  */
572 struct cdr_object_fn_table bridged_pending_state_fn_table = {
573         .name = "Pending",
574         .init_function = pending_state_init_function,
575         .process_party_a = pending_state_process_party_a,
576         .process_dial_begin = pending_state_process_dial_begin,
577         .process_dial_end = base_process_dial_end,
578         .process_bridge_enter = pending_state_process_bridge_enter,
579         .process_bridge_leave = base_process_bridge_leave,
580 };
581
582 static void finalized_state_init_function(struct cdr_object *cdr);
583 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
584
585 /*!
586  * \brief The virtual table for the finalized state.
587  *
588  * Once in the finalized state, the CDR is done. No modifications can be made
589  * to the CDR.
590  */
591 struct cdr_object_fn_table finalized_state_fn_table = {
592         .name = "Finalized",
593         .init_function = finalized_state_init_function,
594         .process_party_a = finalized_state_process_party_a,
595 };
596
597 /*! \brief A wrapper object around a snapshot.
598  * Fields that are mutable by the CDR engine are replicated here.
599  */
600 struct cdr_object_snapshot {
601         struct ast_channel_snapshot *snapshot;  /*!< The channel snapshot */
602         char userfield[AST_MAX_USER_FIELD];     /*!< Userfield for the channel */
603         unsigned int flags;                     /*!< Specific flags for this party */
604         struct varshead variables;              /*!< CDR variables for the channel */
605 };
606
607 /*! \brief An in-memory representation of an active CDR */
608 struct cdr_object {
609         struct cdr_object_snapshot party_a;     /*!< The Party A information */
610         struct cdr_object_snapshot party_b;     /*!< The Party B information */
611         struct cdr_object_fn_table *fn_table;   /*!< The current virtual table */
612
613         enum ast_cdr_disposition disposition;   /*!< The disposition of the CDR */
614         struct timeval start;                   /*!< When this CDR was created */
615         struct timeval answer;                  /*!< Either when the channel was answered, or when the path between channels was established */
616         struct timeval end;                     /*!< When this CDR was finalized */
617         unsigned int sequence;                  /*!< A monotonically increasing number for each CDR */
618         struct ast_flags flags;                 /*!< Flags on the CDR */
619         AST_DECLARE_STRING_FIELDS(
620                 AST_STRING_FIELD(linkedid);         /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
621                 AST_STRING_FIELD(name);             /*!< Channel name of party A. Cached here as the party A address may change */
622                 AST_STRING_FIELD(bridge);           /*!< The bridge the party A happens to be in. */
623                 AST_STRING_FIELD(appl);             /*!< The last accepted application party A was in */
624                 AST_STRING_FIELD(data);             /*!< The data for the last accepted application party A was in */
625         );
626         struct cdr_object *next;                /*!< The next CDR object in the chain */
627         struct cdr_object *last;                /*!< The last CDR object in the chain */
628 };
629
630 /*!
631  * \brief Copy variables from one list to another
632  * \param to_list destination
633  * \param from_list source
634  * \retval The number of copied variables
635  */
636 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
637 {
638         struct ast_var_t *variables, *newvariable = NULL;
639         const char *var, *val;
640         int x = 0;
641
642         AST_LIST_TRAVERSE(from_list, variables, entries) {
643                 if (variables &&
644                     (var = ast_var_name(variables)) && (val = ast_var_value(variables)) &&
645                     !ast_strlen_zero(var) && !ast_strlen_zero(val)) {
646                         newvariable = ast_var_assign(var, val);
647                         AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
648                         x++;
649                 }
650         }
651
652         return x;
653 }
654
655 /*!
656  * \brief Delete all variables from a variable list
657  * \param headp The head pointer to the variable list to delete
658  */
659 static void free_variables(struct varshead *headp)
660 {
661         struct ast_var_t *vardata;
662
663         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
664                 ast_var_delete(vardata);
665         }
666 }
667
668 /*!
669  * \brief Copy a snapshot and its details
670  * \param dst The destination
671  * \param src The source
672  */
673 static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
674 {
675         if (dst->snapshot) {
676                 ao2_t_ref(dst->snapshot, -1, "release old snapshot during copy");
677         }
678         dst->snapshot = src->snapshot;
679         ao2_t_ref(dst->snapshot, +1, "bump new snapshot during copy");
680         strcpy(dst->userfield, src->userfield);
681         dst->flags = src->flags;
682         copy_variables(&dst->variables, &src->variables);
683 }
684
685 /*!
686  * \brief Transition a \ref cdr_object to a new state
687  * \param cdr The \ref cdr_object to transition
688  * \param fn_table The \ref cdr_object_fn_table state to go to
689  */
690 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
691 {
692         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
693
694         CDR_DEBUG(mod_cfg, "%p - Transitioning CDR for %s from state %s to %s\n",
695                 cdr, cdr->party_a.snapshot->name,
696                 cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
697         cdr->fn_table = fn_table;
698         if (cdr->fn_table->init_function) {
699                 cdr->fn_table->init_function(cdr);
700         }
701 }
702 /*! \internal
703  * \brief Hash function for containers of CDRs indexing by Party A name */
704 static int cdr_object_channel_hash_fn(const void *obj, const int flags)
705 {
706         const struct cdr_object *cdr = obj;
707         const char *name = (flags & OBJ_KEY) ? obj : cdr->name;
708         return ast_str_case_hash(name);
709 }
710
711 /*! \internal
712  * \brief Comparison function for containers of CDRs indexing by Party A name
713  */
714 static int cdr_object_channel_cmp_fn(void *obj, void *arg, int flags)
715 {
716         struct cdr_object *left = obj;
717         struct cdr_object *right = arg;
718         const char *match = (flags & OBJ_KEY) ? arg : right->name;
719         return strcasecmp(left->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
720 }
721
722 /*! \internal
723  * \brief Hash function for containers of CDRs indexing by bridge ID
724  */
725 static int cdr_object_bridge_hash_fn(const void *obj, const int flags)
726 {
727         const struct cdr_object *cdr = obj;
728         const char *id = (flags & OBJ_KEY) ? obj : cdr->bridge;
729         return ast_str_case_hash(id);
730 }
731
732 /*! \internal
733  * \brief Comparison function for containers of CDRs indexing by bridge. Note
734  * that we expect there to be collisions, as a single bridge may have multiple
735  * CDRs active at one point in time
736  */
737 static int cdr_object_bridge_cmp_fn(void *obj, void *arg, int flags)
738 {
739         struct cdr_object *left = obj;
740         struct cdr_object *right = arg;
741         struct cdr_object *it_cdr;
742         const char *match = (flags & OBJ_KEY) ? arg : right->bridge;
743         for (it_cdr = left; it_cdr; it_cdr = it_cdr->next) {
744                 if (!strcasecmp(it_cdr->bridge, match)) {
745                         return CMP_MATCH;
746                 }
747         }
748         return 0;
749 }
750
751 /*!
752  * \brief \ref cdr_object Destructor
753  */
754 static void cdr_object_dtor(void *obj)
755 {
756         struct cdr_object *cdr = obj;
757         struct ast_var_t *it_var;
758
759         if (!cdr) {
760                 return;
761         }
762
763         ao2_cleanup(cdr->party_a.snapshot);
764         ao2_cleanup(cdr->party_b.snapshot);
765         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
766                 ast_var_delete(it_var);
767         }
768         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
769                 ast_var_delete(it_var);
770         }
771         ast_string_field_free_memory(cdr);
772
773         if (cdr->next) {
774                 ao2_cleanup(cdr->next);
775         }
776 }
777
778 /*!
779  * \brief \ref cdr_object constructor
780  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
781  *
782  * This implicitly sets the state of the newly created CDR to the Single state
783  * (\ref single_state_fn_table)
784  */
785 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
786 {
787         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
788         struct cdr_object *cdr;
789
790         ast_assert(chan != NULL);
791
792         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
793         if (!cdr) {
794                 return NULL;
795         }
796         cdr->last = cdr;
797         if (ast_string_field_init(cdr, 64)) {
798                 return NULL;
799         }
800         ast_string_field_set(cdr, name, chan->name);
801         ast_string_field_set(cdr, linkedid, chan->linkedid);
802         cdr->disposition = AST_CDR_NULL;
803         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
804
805         cdr->party_a.snapshot = chan;
806         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
807
808         CDR_DEBUG(mod_cfg, "%p - Created CDR for channel %s\n", cdr, chan->name);
809
810         cdr_object_transition_state(cdr, &single_state_fn_table);
811
812         return cdr;
813 }
814
815 /*!
816  * \brief Create a new \ref cdr_object and append it to an existing chain
817  * \param cdr The \ref cdr_object to append to
818  */
819 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
820 {
821         struct cdr_object *new_cdr;
822         struct cdr_object *it_cdr;
823         struct cdr_object *cdr_last;
824
825         cdr_last = cdr->last;
826         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
827         if (!new_cdr) {
828                 return NULL;
829         }
830         new_cdr->disposition = AST_CDR_NULL;
831
832         /* Copy over the linkedid, as it may have changed */
833         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
834         ast_string_field_set(new_cdr, appl, cdr_last->appl);
835         ast_string_field_set(new_cdr, data, cdr_last->data);
836
837         /* Copy over other Party A information */
838         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
839
840         /* Append the CDR to the end of the list */
841         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
842                 it_cdr->last = new_cdr;
843         }
844         it_cdr->last = new_cdr;
845         it_cdr->next = new_cdr;
846
847         return new_cdr;
848 }
849
850 /*!
851  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
852  * that was created as the result of a dial operation
853  *
854  * \retval 0 the channel was not created as the result of a dial
855  * \retval 1 the channel was created as the result of a dial
856  */
857 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
858 {
859         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
860                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
861 }
862
863 /*!
864  * \brief Given two CDR snapshots, figure out who should be Party A for the
865  * resulting CDR
866  * \param left One of the snapshots
867  * \param right The other snapshot
868  * \retval The snapshot that won
869  */
870 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
871 {
872         /* Check whether or not the party is dialed. A dialed party is never the
873          * Party A with a party that was not dialed.
874          */
875         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
876                 return left;
877         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
878                 return right;
879         }
880
881         /* Try the Party A flag */
882         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
883                 return left;
884         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
885                 return right;
886         }
887
888         /* Neither party is dialed and neither has the Party A flag - defer to
889          * creation time */
890         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
891                 return left;
892         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
893                 return right;
894         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
895                         return right;
896         } else {
897                 /* Okay, fine, take the left one */
898                 return left;
899         }
900 }
901
902 /*!
903  * Compute the duration for a \ref cdr_object
904  */
905 static long cdr_object_get_duration(struct cdr_object *cdr)
906 {
907         if (ast_tvzero(cdr->end)) {
908                 return (long)(ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
909         } else {
910                 return (long)(ast_tvdiff_ms(cdr->end, cdr->start) / 1000);
911         }
912 }
913
914 /*!
915  * \brief Compute the billsec for a \ref cdr_object
916  */
917 static long cdr_object_get_billsec(struct cdr_object *cdr)
918 {
919         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
920         long int ms;
921
922         if (ast_tvzero(cdr->answer)) {
923                 return 0;
924         }
925         ms = ast_tvdiff_ms(cdr->end, cdr->answer);
926         if (ast_test_flag(&mod_cfg->general->settings, CDR_INITIATED_SECONDS)
927                 && (ms % 1000 >= 500)) {
928                 ms = (ms / 1000) + 1;
929         } else {
930                 ms = ms / 1000;
931         }
932
933         return ms;
934 }
935
936 /*!
937  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
938  * suitable for consumption by the registered CDR backends
939  * \param cdr The \ref cdr_object to convert to a public record
940  * \retval A chain of \ref ast_cdr objects on success
941  * \retval NULL on failure
942  */
943 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
944 {
945         struct ast_cdr *pub_cdr = NULL, *cdr_prev;
946         struct ast_var_t *it_var, *it_copy_var;
947         struct ast_channel_snapshot *party_a;
948         struct ast_channel_snapshot *party_b;
949
950         while (cdr) {
951                 struct ast_cdr *cdr_copy;
952
953                 /* Don't create records for CDRs where the party A was a dialed channel */
954                 if (snapshot_is_dialed(cdr->party_a.snapshot)) {
955                         cdr = cdr->next;
956                         continue;
957                 }
958
959                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
960                 if (!cdr_copy) {
961                         ast_free(pub_cdr);
962                         return NULL;
963                 }
964
965                 party_a = cdr->party_a.snapshot;
966                 party_b = cdr->party_b.snapshot;
967
968                 /* Party A */
969                 ast_assert(party_a != NULL);
970                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
971                 cdr_copy->amaflags = party_a->amaflags;
972                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
973                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
974                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
975                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
976                 ast_copy_string(cdr_copy->lastapp, cdr->appl, sizeof(cdr_copy->lastapp));
977                 ast_copy_string(cdr_copy->lastdata, cdr->data, sizeof(cdr_copy->lastdata));
978                 ast_copy_string(cdr_copy->dst, party_a->exten, sizeof(cdr_copy->dst));
979                 ast_copy_string(cdr_copy->dcontext, party_a->context, sizeof(cdr_copy->dcontext));
980
981                 /* Party B */
982                 if (party_b) {
983                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
984                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
985                         if (!ast_strlen_zero(cdr->party_b.userfield)) {
986                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", cdr->party_a.userfield, cdr->party_b.userfield);
987                         }
988                 }
989                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(cdr->party_a.userfield)) {
990                         ast_copy_string(cdr_copy->userfield, cdr->party_a.userfield, sizeof(cdr_copy->userfield));
991                 }
992
993                 /* Timestamps/durations */
994                 cdr_copy->start = cdr->start;
995                 cdr_copy->answer = cdr->answer;
996                 cdr_copy->end = cdr->end;
997                 cdr_copy->billsec = cdr_object_get_billsec(cdr);
998                 cdr_copy->duration = cdr_object_get_duration(cdr);
999
1000                 /* Flags and IDs */
1001                 ast_copy_flags(cdr_copy, &cdr->flags, AST_FLAGS_ALL);
1002                 ast_copy_string(cdr_copy->linkedid, cdr->linkedid, sizeof(cdr_copy->linkedid));
1003                 cdr_copy->disposition = cdr->disposition;
1004                 cdr_copy->sequence = cdr->sequence;
1005
1006                 /* Variables */
1007                 copy_variables(&cdr_copy->varshead, &cdr->party_a.variables);
1008                 AST_LIST_TRAVERSE(&cdr->party_b.variables, it_var, entries) {
1009                         int found = 0;
1010                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1011                                 if (!strcmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1012                                         found = 1;
1013                                         break;
1014                                 }
1015                         }
1016                         if (!found) {
1017                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, ast_var_assign(ast_var_name(it_var),
1018                                                 ast_var_value(it_var)), entries);
1019                         }
1020                 }
1021
1022                 if (!pub_cdr) {
1023                         pub_cdr = cdr_copy;
1024                         cdr_prev = pub_cdr;
1025                 } else {
1026                         cdr_prev->next = cdr_copy;
1027                         cdr_prev = cdr_copy;
1028                 }
1029                 cdr = cdr->next;
1030         }
1031
1032         return pub_cdr;
1033 }
1034
1035 /*!
1036  * \brief Dispatch a CDR.
1037  * \param cdr The \ref cdr_object to dispatch
1038  *
1039  * This will create a \ref ast_cdr object and publish it to the various backends
1040  */
1041 static void cdr_object_dispatch(struct cdr_object *cdr)
1042 {
1043         RAII_VAR(struct module_config *, mod_cfg,
1044                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1045         struct ast_cdr *pub_cdr;
1046
1047         CDR_DEBUG(mod_cfg, "%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1048                         cdr->party_a.snapshot->name,
1049                         cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1050         pub_cdr = cdr_object_create_public_records(cdr);
1051         cdr_detach(pub_cdr);
1052 }
1053
1054 /*!
1055  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1056  * \param cdr The \ref cdr_object
1057  * \param hangupcause The Asterisk hangup cause code
1058  */
1059 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1060 {
1061         RAII_VAR(struct module_config *, mod_cfg,
1062                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1063
1064         /* Change the disposition based on the hang up cause */
1065         switch (hangupcause) {
1066         case AST_CAUSE_BUSY:
1067                 cdr->disposition = AST_CDR_BUSY;
1068                 break;
1069         case AST_CAUSE_CONGESTION:
1070                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1071                         cdr->disposition = AST_CDR_FAILED;
1072                 } else {
1073                         cdr->disposition = AST_CDR_CONGESTION;
1074                 }
1075                 break;
1076         case AST_CAUSE_NO_ROUTE_DESTINATION:
1077         case AST_CAUSE_UNREGISTERED:
1078                 cdr->disposition = AST_CDR_FAILED;
1079                 break;
1080         case AST_CAUSE_NORMAL_CLEARING:
1081         case AST_CAUSE_NO_ANSWER:
1082                 cdr->disposition = AST_CDR_NOANSWER;
1083                 break;
1084         default:
1085                 break;
1086         }
1087 }
1088
1089 /*!
1090  * \brief Finalize a CDR.
1091  *
1092  * This function is safe to call multiple times. Note that you can call this
1093  * explicitly before going to the finalized state if there's a chance the CDR
1094  * will be re-activated, in which case the \ref cdr_object's end time should be
1095  * cleared. This function is implicitly called when a CDR transitions to the
1096  * finalized state and right before it is dispatched
1097  *
1098  * \param cdr_object The CDR to finalize
1099  */
1100 static void cdr_object_finalize(struct cdr_object *cdr)
1101 {
1102         RAII_VAR(struct module_config *, mod_cfg,
1103                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1104
1105         if (!ast_tvzero(cdr->end)) {
1106                 return;
1107         }
1108         cdr->end = ast_tvnow();
1109
1110         if (cdr->disposition == AST_CDR_NULL) {
1111                 if (!ast_tvzero(cdr->answer)) {
1112                         cdr->disposition = AST_CDR_ANSWERED;
1113                 } else if (cdr->party_a.snapshot->hangupcause) {
1114                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1115                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1116                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1117                 } else {
1118                         cdr->disposition = AST_CDR_FAILED;
1119                 }
1120         }
1121
1122         ast_debug(1, "Finalized CDR for %s - start %ld.%ld answer %ld.%ld end %ld.%ld dispo %s\n",
1123                         cdr->party_a.snapshot->name,
1124                         cdr->start.tv_sec,
1125                         cdr->start.tv_usec,
1126                         cdr->answer.tv_sec,
1127                         cdr->answer.tv_usec,
1128                         cdr->end.tv_sec,
1129                         cdr->end.tv_usec,
1130                         ast_cdr_disp2str(cdr->disposition));
1131 }
1132
1133 /*!
1134  * \brief Check to see if a CDR needs to move to the finalized state because
1135  * its Party A hungup.
1136  */
1137 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1138 {
1139         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_ZOMBIE)
1140                 && cdr->fn_table != &finalized_state_fn_table) {
1141                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1142         }
1143 }
1144
1145 /*!
1146  * \brief Check to see if a CDR needs to be answered based on its Party A.
1147  * Note that this is safe to call as much as you want - we won't answer twice
1148  */
1149 static void cdr_object_check_party_a_answer(struct cdr_object *cdr) {
1150         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1151
1152         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1153                 cdr->answer = ast_tvnow();
1154                 CDR_DEBUG(mod_cfg, "%p - Set answered time to %ld.%ld\n", cdr,
1155                         cdr->answer.tv_sec,
1156                         cdr->answer.tv_usec);
1157         }
1158 }
1159
1160 /*!
1161  * \internal
1162  * \brief Set a variable on a CDR object
1163  *
1164  * \param headp The header pointer to the variable to set
1165  * \param name The name of the variable
1166  * \param value The value of the variable
1167  *
1168  * CDRs that are in a hungup state cannot have their variables set.
1169  */
1170 static void set_variable(struct varshead *headp, const char *name, const char *value)
1171 {
1172         struct ast_var_t *newvariable;
1173
1174         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1175                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1176                         AST_LIST_REMOVE_CURRENT(entries);
1177                         ast_var_delete(newvariable);
1178                         break;
1179                 }
1180         }
1181         AST_LIST_TRAVERSE_SAFE_END;
1182
1183         if (value) {
1184                 newvariable = ast_var_assign(name, value);
1185                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1186         }
1187 }
1188
1189 /* \brief Set Caller ID information on a CDR */
1190 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1191 {
1192         if (!old_snapshot->snapshot) {
1193                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1194                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1195                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1196                 return;
1197         }
1198         if (!strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1199                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1200         }
1201         if (!strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1202                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1203         }
1204         if (!strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1205                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1206         }
1207 }
1208
1209 /*!
1210  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1211  * a new \ref ast_channel_snapshot
1212  * \param old_snapshot The old \ref cdr_object_snapshot
1213  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1214  */
1215 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1216                 struct ast_channel_snapshot *new_snapshot)
1217 {
1218         cdr_object_update_cid(old_snapshot, new_snapshot);
1219         if (old_snapshot->snapshot) {
1220                 ao2_t_ref(old_snapshot->snapshot, -1, "Drop ref for swap");
1221         }
1222         ao2_t_ref(new_snapshot, +1, "Bump ref for swap");
1223         old_snapshot->snapshot = new_snapshot;
1224 }
1225
1226 /* BASE METHOD IMPLEMENTATIONS */
1227
1228 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1229 {
1230         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1231
1232         ast_assert(strcmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1233         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1234
1235         /* When Party A is originated to an application and the application exits, the stack
1236          * will attempt to clear the application and restore the dummy originate application
1237          * of "AppDialX". Prevent that, and any other application changes we might not want
1238          * here.
1239          */
1240         if (!ast_strlen_zero(snapshot->appl) && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1241                 ast_string_field_set(cdr, appl, snapshot->appl);
1242                 ast_string_field_set(cdr, data, snapshot->data);
1243         }
1244
1245         ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1246         cdr_object_check_party_a_answer(cdr);
1247         cdr_object_check_party_a_hangup(cdr);
1248
1249         return 0;
1250 }
1251
1252 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1253 {
1254         /* In general, most things shouldn't get a bridge leave */
1255         ast_assert(0);
1256         return 1;
1257 }
1258
1259 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1260 {
1261         /* In general, most things shouldn't get a dial end. */
1262         ast_assert(0);
1263         return 0;
1264 }
1265
1266 /* SINGLE STATE */
1267
1268 static void single_state_init_function(struct cdr_object *cdr) {
1269         cdr->start = ast_tvnow();
1270         cdr_object_check_party_a_answer(cdr);
1271 }
1272
1273 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1274 {
1275         /* This should never happen! */
1276         ast_assert(cdr->party_b.snapshot == NULL);
1277         ast_assert(0);
1278         return;
1279 }
1280
1281 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1282 {
1283         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1284
1285         if (caller && !strcmp(cdr->party_a.snapshot->name, caller->name)) {
1286                 cdr_object_swap_snapshot(&cdr->party_a, caller);
1287                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1288                                 cdr->party_a.snapshot->name);
1289                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1290                 CDR_DEBUG(mod_cfg, "%p - Updated Party B %s snapshot\n", cdr,
1291                                 cdr->party_b.snapshot->name);
1292         } else if (!strcmp(cdr->party_a.snapshot->name, peer->name)) {
1293                 /* We're the entity being dialed, i.e., outbound origination */
1294                 cdr_object_swap_snapshot(&cdr->party_a, peer);
1295                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1296                                 cdr->party_a.snapshot->name);
1297         }
1298
1299         cdr_object_transition_state(cdr, &dial_state_fn_table);
1300         return 0;
1301 }
1302
1303 /*!
1304  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1305  * already in the bridge while in the Single state. The goal of this is to find
1306  * a Party B for our CDR.
1307  *
1308  * \param cdr Our \ref cdr_object in the Single state
1309  * \param cand_cdr The \ref cdr_object already in the Bridge state
1310  *
1311  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1312  * Party B
1313  * \retval 1 No party in the cand_cdr could be used as our Party B
1314  */
1315 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1316                 struct cdr_object *cand_cdr)
1317 {
1318         struct cdr_object_snapshot *party_a;
1319
1320         /* Try the candidate CDR's Party A first */
1321         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1322         if (!strcmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1323                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1324                 if (!cand_cdr->party_b.snapshot) {
1325                         /* We just stole them - finalize their CDR. Note that this won't
1326                          * transition their state, it just sets the end time and the
1327                          * disposition - if we need to re-activate them later, we can.
1328                          */
1329                         cdr_object_finalize(cand_cdr);
1330                 }
1331                 return 0;
1332         }
1333
1334         /* Try their Party B */
1335         if (!cand_cdr->party_b.snapshot) {
1336                 return 1;
1337         }
1338         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1339         if (!strcmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1340                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1341                 return 0;
1342         }
1343
1344         return 1;
1345 }
1346
1347 static int single_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1348 {
1349         struct ao2_iterator *it_cdrs;
1350         struct cdr_object *cand_cdr_master;
1351         char *bridge_id = ast_strdupa(bridge->uniqueid);
1352         int success = 1;
1353
1354         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1355
1356         /* Get parties in the bridge */
1357         it_cdrs = ao2_callback(active_cdrs_by_bridge, OBJ_MULTIPLE | OBJ_KEY,
1358                         cdr_object_bridge_cmp_fn, bridge_id);
1359         if (!it_cdrs) {
1360                 /* No one in the bridge yet! */
1361                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1362                 return 0;
1363         }
1364
1365         while ((cand_cdr_master = ao2_iterator_next(it_cdrs))) {
1366                 struct cdr_object *cand_cdr;
1367
1368                 ao2_lock(cand_cdr_master);
1369                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1370                         /* Skip any records that are not in a bridge or in this bridge.
1371                          * I'm not sure how that would happen, but it pays to be careful. */
1372                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1373                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1374                                 continue;
1375                         }
1376
1377                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1378                                 continue;
1379                         }
1380                         /* We successfully got a party B - break out */
1381                         success = 0;
1382                         break;
1383                 }
1384                 ao2_unlock(cand_cdr_master);
1385                 ao2_t_ref(cand_cdr_master, -1, "Drop iterator reference");
1386         }
1387         ao2_iterator_destroy(it_cdrs);
1388
1389         /* We always transition state, even if we didn't get a peer */
1390         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1391
1392         /* Success implies that we have a Party B */
1393         return success;
1394 }
1395
1396 /* DIAL STATE */
1397
1398 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1399 {
1400         ast_assert(snapshot != NULL);
1401
1402         if (!cdr->party_b.snapshot || strcmp(cdr->party_b.snapshot->name, snapshot->name)) {
1403                 return;
1404         }
1405         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1406
1407         /* If party B hangs up, finalize this CDR */
1408         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_ZOMBIE)) {
1409                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1410         }
1411 }
1412
1413 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1414 {
1415         /* Don't process a begin dial here. A party A already in the dial state will
1416          * who receives a dial begin for something else will be handled by the
1417          * message router callback and will add a new CDR for the party A */
1418         return 1;
1419 }
1420
1421 /*! \internal \brief Convert a dial status to a CDR disposition */
1422 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1423 {
1424         RAII_VAR(struct module_config *, mod_cfg,
1425                 ao2_global_obj_ref(module_configs), ao2_cleanup);
1426
1427         if (!strcmp(dial_status, "ANSWER")) {
1428                 return AST_CDR_ANSWERED;
1429         } else if (!strcmp(dial_status, "BUSY")) {
1430                 return AST_CDR_BUSY;
1431         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1432                 return AST_CDR_NOANSWER;
1433         } else if (!strcmp(dial_status, "CONGESTION")) {
1434                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1435                         return AST_CDR_FAILED;
1436                 } else {
1437                         return AST_CDR_CONGESTION;
1438                 }
1439         } else if (!strcmp(dial_status, "FAILED")) {
1440                 return AST_CDR_FAILED;
1441         }
1442         return AST_CDR_FAILED;
1443 }
1444
1445 static int dial_state_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1446 {
1447         RAII_VAR(struct module_config *, mod_cfg,
1448                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1449         struct ast_channel_snapshot *party_a;
1450
1451         if (caller) {
1452                 party_a = caller;
1453         } else {
1454                 party_a = peer;
1455         }
1456         ast_assert(!strcmp(cdr->party_a.snapshot->name, party_a->name));
1457         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1458
1459         if (cdr->party_b.snapshot) {
1460                 if (strcmp(cdr->party_b.snapshot->name, peer->name)) {
1461                         /* Not the status for this CDR - defer back to the message router */
1462                         return 1;
1463                 }
1464                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1465         }
1466
1467         /* Set the disposition based on the dial string. */
1468         cdr->disposition = dial_status_to_disposition(dial_status);
1469         if (cdr->disposition == AST_CDR_ANSWERED) {
1470                 /* Switch to dial pending to wait and see what the caller does */
1471                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1472         } else {
1473                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1474         }
1475
1476         return 0;
1477 }
1478
1479 static int dial_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1480 {
1481         struct ao2_iterator *it_cdrs;
1482         char *bridge_id = ast_strdupa(bridge->uniqueid);
1483         struct cdr_object *cand_cdr_master;
1484         int success = 1;
1485
1486         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1487
1488         /* Get parties in the bridge */
1489         it_cdrs = ao2_callback(active_cdrs_by_bridge, OBJ_MULTIPLE | OBJ_KEY,
1490                         cdr_object_bridge_cmp_fn, bridge_id);
1491         if (!it_cdrs) {
1492                 /* No one in the bridge yet! */
1493                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1494                 return 0;
1495         }
1496
1497         while ((cand_cdr_master = ao2_iterator_next(it_cdrs))) {
1498                 struct cdr_object *cand_cdr;
1499
1500                 ao2_lock(cand_cdr_master);
1501                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1502                         /* Skip any records that are not in a bridge or in this bridge.
1503                          * I'm not sure how that would happen, but it pays to be careful. */
1504                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1505                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1506                                 continue;
1507                         }
1508
1509                         /* Skip any records that aren't our Party B */
1510                         if (strcmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1511                                 continue;
1512                         }
1513
1514                         cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1515                         /* If they have a Party B, they joined up with someone else as their
1516                          * Party A. Don't finalize them as they're active. Otherwise, we
1517                          * have stolen them so they need to be finalized.
1518                          */
1519                         if (!cand_cdr->party_b.snapshot) {
1520                                 cdr_object_finalize(cand_cdr);
1521                         }
1522                         success = 0;
1523                         break;
1524                 }
1525                 ao2_unlock(cand_cdr_master);
1526                 ao2_t_ref(cand_cdr_master, -1, "Drop iterator reference");
1527         }
1528         ao2_iterator_destroy(it_cdrs);
1529
1530         /* We always transition state, even if we didn't get a peer */
1531         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1532
1533         /* Success implies that we have a Party B */
1534         return success;
1535 }
1536
1537 /* DIALED PENDING STATE */
1538
1539 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1540 {
1541         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1542          * that means we need a new CDR; otherwise, switch us over to single.
1543          */
1544         if (strcmp(snapshot->context, cdr->party_a.snapshot->context)
1545                 || strcmp(snapshot->exten, cdr->party_a.snapshot->exten)
1546                 || snapshot->priority != cdr->party_a.snapshot->priority
1547                 || strcmp(snapshot->appl, cdr->party_a.snapshot->appl)) {
1548                 if (cdr->party_b.snapshot) {
1549                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1550                         cdr->fn_table->process_party_a(cdr, snapshot);
1551                         return 1;
1552                 } else {
1553                         cdr_object_transition_state(cdr, &single_state_fn_table);
1554                         cdr->fn_table->process_party_a(cdr, snapshot);
1555                         return 0;
1556                 }
1557         }
1558         base_process_party_a(cdr, snapshot);
1559         return 0;
1560 }
1561
1562 static int dialed_pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1563 {
1564         cdr_object_transition_state(cdr, &dial_state_fn_table);
1565         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1566 }
1567
1568 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1569 {
1570         struct cdr_object *new_cdr;
1571
1572         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1573         new_cdr = cdr_object_create_and_append(cdr);
1574         cdr_object_transition_state(cdr, &single_state_fn_table);
1575         return new_cdr->fn_table->process_dial_begin(cdr, caller, peer);
1576 }
1577
1578 /* BRIDGE STATE */
1579
1580 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1581 {
1582         if (!cdr->party_b.snapshot || strcmp(cdr->party_b.snapshot->name, snapshot->name)) {
1583                 return;
1584         }
1585         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1586
1587         /* If party B hangs up, finalize this CDR */
1588         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_ZOMBIE)) {
1589                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1590         }
1591 }
1592
1593 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1594 {
1595         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1596                 return 1;
1597         }
1598         if (strcmp(cdr->party_a.snapshot->name, channel->name)
1599                         && cdr->party_b.snapshot
1600                         && strcmp(cdr->party_b.snapshot->name, channel->name)) {
1601                 return 1;
1602         }
1603         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1604
1605         return 0;
1606 }
1607
1608 /* PENDING STATE */
1609
1610 static void pending_state_init_function(struct cdr_object *cdr)
1611 {
1612         ast_cdr_set_property(cdr->name, AST_CDR_FLAG_DISABLE);
1613 }
1614
1615 static int pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1616 {
1617         if (ast_test_flag(&snapshot->flags, AST_FLAG_ZOMBIE)) {
1618                 return 0;
1619         }
1620
1621         /* Ignore if we don't get a CEP change */
1622         if (!strcmp(snapshot->context, cdr->party_a.snapshot->context)
1623                 && !strcmp(snapshot->exten, cdr->party_a.snapshot->exten)
1624                 && snapshot->priority == cdr->party_a.snapshot->priority) {
1625                 return 0;
1626         }
1627
1628         cdr_object_transition_state(cdr, &single_state_fn_table);
1629         ast_cdr_clear_property(cdr->name, AST_CDR_FLAG_DISABLE);
1630         cdr->fn_table->process_party_a(cdr, snapshot);
1631         return 0;
1632 }
1633
1634 static int pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1635 {
1636         cdr_object_transition_state(cdr, &single_state_fn_table);
1637         ast_cdr_clear_property(cdr->name, AST_CDR_FLAG_DISABLE);
1638         return cdr->fn_table->process_dial_begin(cdr, caller, peer);
1639 }
1640
1641 static int pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1642 {
1643         cdr_object_transition_state(cdr, &single_state_fn_table);
1644         ast_cdr_clear_property(cdr->name, AST_CDR_FLAG_DISABLE);
1645         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1646 }
1647
1648 /* FINALIZED STATE */
1649
1650 static void finalized_state_init_function(struct cdr_object *cdr)
1651 {
1652         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1653
1654         if (!ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)) {
1655                 return;
1656         }
1657
1658         cdr_object_finalize(cdr);
1659 }
1660
1661 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1662 {
1663         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_ZOMBIE)) {
1664                 cdr_object_finalize(cdr);
1665         }
1666
1667         /* Indicate that, if possible, we should get a new CDR */
1668         return 1;
1669 }
1670
1671 /* TOPIC ROUTER CALLBACKS */
1672
1673 /*!
1674  * \brief Handler for Stasis-Core dial messages
1675  * \param data Passed on
1676  * \param sub The stasis subscription for this message callback
1677  * \param topic The topic this message was published for
1678  * \param message The message
1679  */
1680 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message)
1681 {
1682         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1683         RAII_VAR(struct cdr_object *, cdr_caller, NULL, ao2_cleanup);
1684         RAII_VAR(struct cdr_object *, cdr_peer, NULL, ao2_cleanup);
1685         struct cdr_object *cdr;
1686         struct ast_multi_channel_blob *payload = stasis_message_data(message);
1687         struct ast_channel_snapshot *caller;
1688         struct ast_channel_snapshot *peer;
1689         struct cdr_object_snapshot *party_a;
1690         struct cdr_object_snapshot *party_b;
1691         struct cdr_object *it_cdr;
1692         struct ast_json *dial_status_blob;
1693         const char *dial_status = NULL;
1694         int res = 1;
1695
1696         CDR_DEBUG(mod_cfg, "Dial message: %u.%08u\n", (unsigned int)stasis_message_timestamp(message)->tv_sec, (unsigned int)stasis_message_timestamp(message)->tv_usec);
1697         ast_assert(payload != NULL);
1698
1699         caller = ast_multi_channel_blob_get_channel(payload, "caller");
1700         peer = ast_multi_channel_blob_get_channel(payload, "peer");
1701         if (!peer && !caller) {
1702                 return;
1703         }
1704         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
1705         if (dial_status_blob) {
1706                 dial_status = ast_json_string_get(dial_status_blob);
1707         }
1708
1709         /* Figure out who is running this show */
1710         if (caller) {
1711                 cdr_caller = ao2_find(active_cdrs_by_channel, caller->name, OBJ_KEY);
1712         }
1713         if (peer) {
1714                 cdr_peer = ao2_find(active_cdrs_by_channel, peer->name, OBJ_KEY);
1715         }
1716         if (cdr_caller && cdr_peer) {
1717                 party_a = cdr_object_pick_party_a(&cdr_caller->party_a, &cdr_peer->party_a);
1718                 if (!strcmp(party_a->snapshot->name, cdr_caller->party_a.snapshot->name)) {
1719                         cdr = cdr_caller;
1720                         party_b = &cdr_peer->party_a;
1721                 } else {
1722                         cdr = cdr_peer;
1723                         party_b = &cdr_caller->party_a;
1724                 }
1725         } else if (cdr_caller) {
1726                 cdr = cdr_caller;
1727                 party_a = &cdr_caller->party_a;
1728                 party_b = NULL;
1729         } else if (cdr_peer) {
1730                 cdr = cdr_peer;
1731                 party_a = NULL;
1732                 party_b = &cdr_peer->party_a;
1733         } else {
1734                 return;
1735         }
1736
1737         ao2_lock(cdr);
1738         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1739                 if (ast_strlen_zero(dial_status)) {
1740                         if (!it_cdr->fn_table->process_dial_begin) {
1741                                 continue;
1742                         }
1743                         CDR_DEBUG(mod_cfg, "%p - Processing Dial Begin message for channel %s, peer %s\n",
1744                                         cdr,
1745                                         party_a ? party_a->snapshot->name : "(none)",
1746                                         party_b ? party_b->snapshot->name : "(none)");
1747                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
1748                                         party_a ? party_a->snapshot : NULL,
1749                                         party_b ? party_b->snapshot : NULL);
1750                 } else {
1751                         if (!it_cdr->fn_table->process_dial_end) {
1752                                 continue;
1753                         }
1754                         CDR_DEBUG(mod_cfg, "%p - Processing Dial End message for channel %s, peer %s\n",
1755                                         cdr,
1756                                         party_a ? party_a->snapshot->name : "(none)",
1757                                         party_b ? party_b->snapshot->name : "(none)");
1758                         it_cdr->fn_table->process_dial_end(it_cdr,
1759                                         party_a ? party_a->snapshot : NULL,
1760                                         party_b ? party_b->snapshot : NULL,
1761                                         dial_status);
1762                 }
1763         }
1764
1765         /* If no CDR handled a dial begin message, make a new one */
1766         if (res && ast_strlen_zero(dial_status)) {
1767                 struct cdr_object *new_cdr;
1768
1769                 new_cdr = cdr_object_create_and_append(cdr);
1770                 if (!new_cdr) {
1771                         return;
1772                 }
1773                 new_cdr->fn_table->process_dial_begin(new_cdr,
1774                                 party_a ? party_a->snapshot : NULL,
1775                                 party_b ? party_b->snapshot : NULL);
1776         }
1777         ao2_unlock(cdr);
1778 }
1779
1780 static int cdr_object_finalize_party_b(void *obj, void *arg, int flags)
1781 {
1782         struct cdr_object *cdr = obj;
1783         struct ast_channel_snapshot *party_b = arg;
1784         struct cdr_object *it_cdr;
1785         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1786                 if (it_cdr->party_b.snapshot && !strcmp(it_cdr->party_b.snapshot->name, party_b->name)) {
1787                         /* Don't transition to the finalized state - let the Party A do
1788                          * that when its ready
1789                          */
1790                         cdr_object_finalize(it_cdr);
1791                 }
1792         }
1793         return 0;
1794 }
1795
1796 static int cdr_object_update_party_b(void *obj, void *arg, int flags)
1797 {
1798         struct cdr_object *cdr = obj;
1799         struct ast_channel_snapshot *party_b = arg;
1800         struct cdr_object *it_cdr;
1801         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1802                 if (!it_cdr->fn_table->process_party_b) {
1803                         continue;
1804                 }
1805                 if (it_cdr->party_b.snapshot && !strcmp(it_cdr->party_b.snapshot->name, party_b->name)) {
1806                         it_cdr->fn_table->process_party_b(it_cdr, party_b);
1807                 }
1808         }
1809         return 0;
1810 }
1811
1812 /*! \internal \brief Filter channel snapshots by technology */
1813 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1814 {
1815         if (!strncmp(snapshot->name, "CBAnn", 5) ||
1816                 !strncmp(snapshot->name, "CBRec", 5)) {
1817                 return 1;
1818         }
1819         return 0;
1820 }
1821
1822 /*! \internal \brief Filter a channel cache update */
1823 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
1824                 struct ast_channel_snapshot *new_snapshot)
1825 {
1826         int ret = 0;
1827
1828         /* Drop cache updates from certain channel technologies */
1829         if (old_snapshot) {
1830                 ret |= filter_channel_snapshot(old_snapshot);
1831         }
1832         if (new_snapshot) {
1833                 ret |= filter_channel_snapshot(new_snapshot);
1834         }
1835
1836         return ret;
1837 }
1838
1839 /*! \brief Determine if we need to add a new CDR based on snapshots */
1840 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
1841                 struct ast_channel_snapshot *new_snapshot)
1842 {
1843         RAII_VAR(struct module_config *, mod_cfg,
1844                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1845
1846         if (!new_snapshot) {
1847                 return 0;
1848         }
1849
1850         if (ast_test_flag(&new_snapshot->flags, AST_FLAG_ZOMBIE)) {
1851                 return 0;
1852         }
1853
1854         /* Auto-fall through will increment the priority but have no application */
1855         if (ast_strlen_zero(new_snapshot->appl)) {
1856                 return 0;
1857         }
1858
1859         if (old_snapshot && !strcmp(old_snapshot->context, new_snapshot->context)
1860                         && !strcmp(old_snapshot->exten, new_snapshot->exten)
1861                         && old_snapshot->priority == new_snapshot->priority
1862                         && !(strcmp(old_snapshot->appl, new_snapshot->appl))) {
1863                 return 0;
1864         }
1865
1866         return 1;
1867 }
1868
1869 /*!
1870  * \brief Handler for Stasis-Core channel cache update messages
1871  * \param data Passed on
1872  * \param sub The stasis subscription for this message callback
1873  * \param topic The topic this message was published for
1874  * \param message The message
1875  */
1876 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message)
1877 {
1878         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
1879         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1880         struct stasis_cache_update *update = stasis_message_data(message);
1881         struct ast_channel_snapshot *old_snapshot;
1882         struct ast_channel_snapshot *new_snapshot;
1883         const char *name;
1884         struct cdr_object *it_cdr;
1885
1886         ast_assert(update != NULL);
1887         if (ast_channel_snapshot_type() != update->type) {
1888                 return;
1889         }
1890
1891         old_snapshot = stasis_message_data(update->old_snapshot);
1892         new_snapshot = stasis_message_data(update->new_snapshot);
1893         name = new_snapshot ? new_snapshot->name : old_snapshot->name;
1894
1895         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
1896                 return;
1897         }
1898
1899         CDR_DEBUG(mod_cfg, "Channel Update message for %s: %u.%08u\n",
1900                         name,
1901                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
1902                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
1903
1904         if (new_snapshot && !old_snapshot) {
1905                 cdr = cdr_object_alloc(new_snapshot);
1906                 if (!cdr) {
1907                         return;
1908                 }
1909                 ao2_link(active_cdrs_by_channel, cdr);
1910         }
1911
1912         /* Handle Party A */
1913         if (!cdr) {
1914                 cdr = ao2_find(active_cdrs_by_channel, name, OBJ_KEY);
1915         }
1916         if (!cdr) {
1917                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
1918         } else {
1919                 ao2_lock(cdr);
1920                 if (new_snapshot) {
1921                         int all_reject = 1;
1922                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1923                                 if (!it_cdr->fn_table->process_party_a) {
1924                                         continue;
1925                                 }
1926                                 CDR_DEBUG(mod_cfg, "%p - Processing new channel snapshot %s\n", it_cdr, new_snapshot->name);
1927                                 all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
1928                         }
1929                         if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
1930                                 /* We're not hung up and we have a new snapshot - we need a new CDR */
1931                                 struct cdr_object *new_cdr;
1932                                 new_cdr = cdr_object_create_and_append(cdr);
1933                                 new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
1934                         }
1935                 } else {
1936                         CDR_DEBUG(mod_cfg, "%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
1937                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1938                                 cdr_object_finalize(it_cdr);
1939                         }
1940                         cdr_object_dispatch(cdr);
1941                         ao2_unlink(active_cdrs_by_channel, cdr);
1942                 }
1943                 ao2_unlock(cdr);
1944         }
1945
1946         /* Handle Party B */
1947         if (new_snapshot) {
1948                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_update_party_b,
1949                         new_snapshot);
1950         } else {
1951                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_finalize_party_b,
1952                         old_snapshot);
1953         }
1954
1955 }
1956
1957 struct bridge_leave_data {
1958         struct ast_bridge_snapshot *bridge;
1959         struct ast_channel_snapshot *channel;
1960 };
1961
1962 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
1963 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, int flags)
1964 {
1965         struct cdr_object *cdr = obj;
1966         struct bridge_leave_data *leave_data = arg;
1967         struct cdr_object *it_cdr;
1968
1969         if (strcmp(cdr->bridge, leave_data->bridge->uniqueid)) {
1970                 return 0;
1971         }
1972         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1973                 if (it_cdr->fn_table != &bridge_state_fn_table) {
1974                         continue;
1975                 }
1976                 if (!it_cdr->party_b.snapshot) {
1977                         continue;
1978                 }
1979                 if (strcmp(it_cdr->party_b.snapshot->name, leave_data->channel->name)) {
1980                         continue;
1981                 }
1982                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, leave_data->bridge, leave_data->channel)) {
1983                         /* Update the end times for this CDR. We don't want to actually
1984                          * finalize it, as the Party A will eventually need to leave, which
1985                          * will switch the records to pending bridged.
1986                          */
1987                         cdr_object_finalize(it_cdr);
1988                 }
1989         }
1990         return 0;
1991 }
1992
1993 /*! \brief Filter bridge messages based on bridge technology */
1994 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
1995 {
1996         /* Ignore holding bridge technology messages. We treat this simply as an application
1997          * that a channel enters into.
1998          */
1999         if (!strcmp(bridge->technology, "holding_bridge")) {
2000                 return 1;
2001         }
2002         return 0;
2003 }
2004
2005 /*!
2006  * \brief Handler for when a channel leaves a bridge
2007  * \param bridge The \ref ast_bridge_snapshot representing the bridge
2008  * \param channel The \ref ast_channel_snapshot representing the channel
2009  */
2010 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2011                 struct stasis_topic *topic, struct stasis_message *message)
2012 {
2013         struct ast_bridge_blob *update = stasis_message_data(message);
2014         struct ast_bridge_snapshot *bridge = update->bridge;
2015         struct ast_channel_snapshot *channel = update->channel;
2016         RAII_VAR(struct module_config *, mod_cfg,
2017                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2018         RAII_VAR(struct cdr_object *, cdr,
2019                         ao2_find(active_cdrs_by_channel, channel->name, OBJ_KEY),
2020                         ao2_cleanup);
2021         struct cdr_object *it_cdr;
2022         struct cdr_object *pending_cdr;
2023         struct bridge_leave_data leave_data = {
2024                 .bridge = bridge,
2025                 .channel = channel,
2026         };
2027         int left_bridge = 0;
2028
2029         if (filter_bridge_messages(bridge)) {
2030                 return;
2031         }
2032
2033         CDR_DEBUG(mod_cfg, "Bridge Leave message: %u.%08u\n", (unsigned int)stasis_message_timestamp(message)->tv_sec, (unsigned int)stasis_message_timestamp(message)->tv_usec);
2034
2035         if (!cdr) {
2036                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2037                 return;
2038         }
2039
2040         /* Party A */
2041         ao2_lock(cdr);
2042         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2043                 if (!it_cdr->fn_table->process_bridge_leave) {
2044                         continue;
2045                 }
2046                 CDR_DEBUG(mod_cfg, "%p - Processing Bridge Leave for %s\n",
2047                                 it_cdr, channel->name);
2048                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2049                         ast_string_field_set(it_cdr, bridge, "");
2050                         left_bridge = 1;
2051                 }
2052         }
2053         if (!left_bridge) {
2054                 ao2_unlock(cdr);
2055                 return;
2056         }
2057
2058         ao2_unlink(active_cdrs_by_bridge, cdr);
2059
2060         /* Create a new pending record. If the channel decides to do something else,
2061          * the pending record will handle it - otherwise, if gets dropped.
2062          */
2063         pending_cdr = cdr_object_create_and_append(cdr);
2064         cdr_object_transition_state(pending_cdr, &bridged_pending_state_fn_table);
2065         ao2_unlock(cdr);
2066
2067         /* Party B */
2068         ao2_callback(active_cdrs_by_bridge, OBJ_NODATA,
2069                         cdr_object_party_b_left_bridge_cb,
2070                         &leave_data);
2071 }
2072
2073 struct bridge_candidate {
2074         struct cdr_object *cdr;                                 /*!< The actual CDR this candidate belongs to, either as A or B */
2075         struct cdr_object_snapshot candidate;   /*!< The candidate for a new pairing */
2076 };
2077
2078 /*! \internal
2079  * \brief Comparison function for \ref bridge_candidate objects
2080  */
2081 static int bridge_candidate_cmp_fn(void *obj, void *arg, int flags)
2082 {
2083         struct bridge_candidate *left = obj;
2084         struct bridge_candidate *right = arg;
2085         const char *match = (flags & OBJ_KEY) ? arg : right->candidate.snapshot->name;
2086         return strcasecmp(left->candidate.snapshot->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
2087 }
2088
2089 /*! \internal
2090  * \brief Hash function for \ref bridge_candidate objects
2091  */
2092 static int bridge_candidate_hash_fn(const void *obj, const int flags)
2093 {
2094         const struct bridge_candidate *bc = obj;
2095         const char *id = (flags & OBJ_KEY) ? obj : bc->candidate.snapshot->name;
2096         return ast_str_case_hash(id);
2097 }
2098
2099 /*! \brief \ref bridge_candidate Destructor */
2100 static void bridge_candidate_dtor(void *obj)
2101 {
2102         struct bridge_candidate *bcand = obj;
2103         ao2_cleanup(bcand->cdr);
2104         ao2_cleanup(bcand->candidate.snapshot);
2105         free_variables(&bcand->candidate.variables);
2106 }
2107
2108 /*!
2109  * \brief \ref bridge_candidate Constructor
2110  * \param cdr The \ref cdr_object that is a candidate for being compared to in
2111  *  a bridge operation
2112  * \param candidate The \ref cdr_object_snapshot candidate snapshot in the CDR
2113  *  that should be used during the operaton
2114  */
2115 static struct bridge_candidate *bridge_candidate_alloc(struct cdr_object *cdr, struct cdr_object_snapshot *candidate)
2116 {
2117         struct bridge_candidate *bcand;
2118
2119         bcand = ao2_alloc(sizeof(*bcand), bridge_candidate_dtor);
2120         if (!bcand) {
2121                 return NULL;
2122         }
2123         bcand->cdr = cdr;
2124         ao2_ref(bcand->cdr, +1);
2125         bcand->candidate.flags = candidate->flags;
2126         strcpy(bcand->candidate.userfield, candidate->userfield);
2127         bcand->candidate.snapshot = candidate->snapshot;
2128         ao2_ref(bcand->candidate.snapshot, +1);
2129         copy_variables(&bcand->candidate.variables, &candidate->variables);
2130
2131         return bcand;
2132 }
2133
2134 /*!
2135  * \internal \brief Build and add bridge candidates based on a CDR
2136  * \param bridge_id The ID of the bridge we need candidates for
2137  * \param candidates The container of \ref bridge_candidate objects
2138  * \param cdr The \ref cdr_object that is our candidate
2139  * \param party_a Non-zero if we should look at the Party A channel; 0 if Party B
2140  */
2141 static void add_candidate_for_bridge(const char *bridge_id,
2142                 struct ao2_container *candidates,
2143                 struct cdr_object *cdr,
2144                 int party_a)
2145 {
2146         struct cdr_object *it_cdr;
2147
2148         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2149                 struct cdr_object_snapshot *party_snapshot;
2150                 RAII_VAR(struct bridge_candidate *, bcand, NULL, ao2_cleanup);
2151
2152                 party_snapshot = party_a ? &it_cdr->party_a : &it_cdr->party_b;
2153
2154                 if (it_cdr->fn_table != &bridge_state_fn_table || strcmp(bridge_id, it_cdr->bridge)) {
2155                         continue;
2156                 }
2157
2158                 if (!party_snapshot->snapshot) {
2159                         continue;
2160                 }
2161
2162                 /* Don't add a party twice */
2163                 bcand = ao2_find(candidates, party_snapshot->snapshot->name, OBJ_KEY);
2164                 if (bcand) {
2165                         continue;
2166                 }
2167
2168                 bcand = bridge_candidate_alloc(it_cdr, party_snapshot);
2169                 if (bcand) {
2170                         ao2_link(candidates, bcand);
2171                 }
2172         }
2173 }
2174
2175 /*!
2176  * \brief Create new \ref bridge_candidate objects for each party currently
2177  * in a bridge
2178  * \param bridge The \param ast_bridge_snapshot for the bridge we're processing
2179  *
2180  * Note that we use two passes here instead of one so that we only create a
2181  * candidate for a party B if they are never a party A in the bridge. Otherwise,
2182  * we don't care about them.
2183  */
2184 static struct ao2_container *create_candidates_for_bridge(struct ast_bridge_snapshot *bridge)
2185 {
2186         struct ao2_container *candidates = ao2_container_alloc(51, bridge_candidate_hash_fn, bridge_candidate_cmp_fn);
2187         char *bridge_id = ast_strdupa(bridge->uniqueid);
2188         struct ao2_iterator *it_cdrs;
2189         struct cdr_object *cand_cdr_master;
2190
2191         if (!candidates) {
2192                 return NULL;
2193         }
2194
2195         /* For each CDR that has a record in the bridge, get their Party A and
2196          * make them a candidate. Note that we do this in two passes as opposed to one so
2197          * that we give preference CDRs where the channel is Party A */
2198         it_cdrs = ao2_callback(active_cdrs_by_bridge, OBJ_MULTIPLE | OBJ_KEY,
2199                         cdr_object_bridge_cmp_fn, bridge_id);
2200         if (!it_cdrs) {
2201                 /* No one in the bridge yet! */
2202                 ao2_cleanup(candidates);
2203                 return NULL;
2204         }
2205         while ((cand_cdr_master = ao2_iterator_next(it_cdrs))) {
2206                 SCOPED_AO2LOCK(lock, cand_cdr_master);
2207                 add_candidate_for_bridge(bridge->uniqueid, candidates, cand_cdr_master, 1);
2208         }
2209         ao2_iterator_destroy(it_cdrs);
2210
2211         /* For each CDR that has a record in the bridge, get their Party B and
2212          * make them a candidate. */
2213         it_cdrs = ao2_callback(active_cdrs_by_bridge, OBJ_MULTIPLE | OBJ_KEY,
2214                         cdr_object_bridge_cmp_fn, bridge_id);
2215         if (!it_cdrs) {
2216                 /* Now it's just an error. */
2217                 ao2_cleanup(candidates);
2218                 return NULL;
2219         }
2220         while ((cand_cdr_master = ao2_iterator_next(it_cdrs))) {
2221                 SCOPED_AO2LOCK(lock, cand_cdr_master);
2222                 add_candidate_for_bridge(bridge->uniqueid, candidates, cand_cdr_master, 0);
2223         }
2224         ao2_iterator_destroy(it_cdrs);
2225
2226         return candidates;
2227 }
2228
2229 /*!
2230  * \internal \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2231  * \note The new CDR will be automatically transitioned to the bridge state
2232  */
2233 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2234                 const char *bridge_id,
2235                 struct cdr_object_snapshot *party_b)
2236 {
2237         struct cdr_object *new_cdr;
2238
2239         new_cdr = cdr_object_create_and_append(cdr);
2240         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2241         cdr_object_check_party_a_answer(new_cdr);
2242         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2243         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2244 }
2245
2246 /*!
2247  * \brief Process a single \ref bridge_candidate. Note that this is called as
2248  * part of an \ref ao2_callback on an \ref ao2_container of \ref bridge_candidate
2249  * objects previously created by \ref create_candidates_for_bridge.
2250  *
2251  * \param obj The \ref bridge_candidate being processed
2252  * \param arg The \ref cdr_object that is being compared against the candidates
2253  *
2254  * The purpose of this function is to create the necessary CDR entries as a
2255  * result of \ref cdr_object having entered the same bridge as the CDR
2256  * represented by \ref bridge_candidate.
2257  */
2258 static int bridge_candidate_process(void *obj, void *arg, int flags)
2259 {
2260         struct bridge_candidate *bcand = obj;
2261         struct cdr_object *cdr = arg;
2262         struct cdr_object_snapshot *party_a;
2263
2264         /* If the candidate is us or someone we've taken on, pass on by */
2265         if (!strcmp(cdr->party_a.snapshot->name, bcand->candidate.snapshot->name)
2266                 || (cdr->party_b.snapshot && !(strcmp(cdr->party_b.snapshot->name, bcand->candidate.snapshot->name)))) {
2267                 return 0;
2268         }
2269
2270         party_a = cdr_object_pick_party_a(&cdr->party_a, &bcand->candidate);
2271         /* We're party A - make a new CDR, append it to us, and set the candidate as
2272          * Party B */
2273         if (!strcmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2274                 bridge_candidate_add_to_cdr(cdr, cdr->bridge, &bcand->candidate);
2275                 return 0;
2276         }
2277
2278         /* We're Party B. Check if the candidate is the CDR's Party A. If so, find out if we
2279          * can add ourselves directly as the Party B, or if we need a new CDR. */
2280         if (!strcmp(bcand->cdr->party_a.snapshot->name, bcand->candidate.snapshot->name)) {
2281                 if (bcand->cdr->party_b.snapshot
2282                                 && strcmp(bcand->cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2283                         bridge_candidate_add_to_cdr(bcand->cdr, cdr->bridge, &cdr->party_a);
2284                 } else {
2285                         cdr_object_snapshot_copy(&bcand->cdr->party_b, &cdr->party_a);
2286                         /* It's possible that this joined at one point and was never chosen
2287                          * as party A. Clear their end time, as it would be set in such a
2288                          * case.
2289                          */
2290                         memset(&bcand->cdr->end, 0, sizeof(bcand->cdr->end));
2291                 }
2292         } else {
2293                 /* We are Party B to a candidate CDR's Party B. Since a candidate
2294                  * CDR will only have a Party B represented here if that channel
2295                  * was never a Party A in the bridge, we have to go looking for
2296                  * that channel's primary CDR record.
2297                  */
2298                 struct cdr_object *b_party = ao2_find(active_cdrs_by_channel, bcand->candidate.snapshot->name, OBJ_KEY);
2299                 if (!b_party) {
2300                         /* Holy cow - no CDR? */
2301                         b_party = cdr_object_alloc(bcand->candidate.snapshot);
2302                         cdr_object_snapshot_copy(&b_party->party_a, &bcand->candidate);
2303                         cdr_object_snapshot_copy(&b_party->party_b, &cdr->party_a);
2304                         cdr_object_check_party_a_answer(b_party);
2305                         ast_string_field_set(b_party, bridge, cdr->bridge);
2306                         cdr_object_transition_state(b_party, &bridge_state_fn_table);
2307                         ao2_link(active_cdrs_by_channel, b_party);
2308                 } else {
2309                         bridge_candidate_add_to_cdr(b_party, cdr->bridge, &cdr->party_a);
2310                 }
2311                 ao2_link(active_cdrs_by_bridge, b_party);
2312                 ao2_ref(b_party, -1);
2313         }
2314
2315         return 0;
2316 }
2317
2318 /*!
2319  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2320  * entered a bridge
2321  * \param cdr The \ref cdr_object that just entered the bridge
2322  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2323  */
2324 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2325 {
2326         RAII_VAR(struct ao2_container *, candidates,
2327                         create_candidates_for_bridge(bridge),
2328                         ao2_cleanup);
2329
2330         if (!candidates) {
2331                 return;
2332         }
2333
2334         ao2_callback(candidates, OBJ_NODATA,
2335                         bridge_candidate_process,
2336                         cdr);
2337
2338         return;
2339 }
2340
2341 /*!
2342  * \brief Handler for Stasis-Core bridge enter messages
2343  * \param data Passed on
2344  * \param sub The stasis subscription for this message callback
2345  * \param topic The topic this message was published for
2346  * \param message The message - hopefully a bridge one!
2347  */
2348 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2349                 struct stasis_topic *topic, struct stasis_message *message)
2350 {
2351         struct ast_bridge_blob *update = stasis_message_data(message);
2352         struct ast_bridge_snapshot *bridge = update->bridge;
2353         struct ast_channel_snapshot *channel = update->channel;
2354         RAII_VAR(struct cdr_object *, cdr,
2355                         ao2_find(active_cdrs_by_channel, channel->name, OBJ_KEY),
2356                         ao2_cleanup);
2357         RAII_VAR(struct module_config *, mod_cfg,
2358                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2359         int res = 1;
2360         struct cdr_object *it_cdr;
2361         struct cdr_object *handled_cdr = NULL;
2362
2363         if (filter_bridge_messages(bridge)) {
2364                 return;
2365         }
2366
2367         CDR_DEBUG(mod_cfg, "Bridge Enter message: %u.%08u\n", (unsigned int)stasis_message_timestamp(message)->tv_sec, (unsigned int)stasis_message_timestamp(message)->tv_usec);
2368
2369         if (!cdr) {
2370                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2371                 return;
2372         }
2373
2374         ao2_lock(cdr);
2375
2376         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2377                 if (it_cdr->fn_table->process_party_a) {
2378                         CDR_DEBUG(mod_cfg, "%p - Updating Party A %s snapshot\n", it_cdr,
2379                                         channel->name);
2380                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2381                 }
2382
2383                 /* Notify all states that they have entered a bridge */
2384                 if (it_cdr->fn_table->process_bridge_enter) {
2385                         CDR_DEBUG(mod_cfg, "%p - Processing bridge enter for %s\n", it_cdr,
2386                                         channel->name);
2387                         res &= it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2388                         if (!res && !handled_cdr) {
2389                                 handled_cdr = it_cdr;
2390                         }
2391                 }
2392         }
2393
2394         if (res) {
2395                 /* We didn't win on any - end this CDR. If someone else comes in later
2396                  * that is Party B to this CDR, it can re-activate this CDR.
2397                  */
2398                 cdr_object_finalize(cdr);
2399         }
2400
2401         /* Create the new matchings, but only for either:
2402          *  * The first CDR in the chain that handled it. This avoids issues with
2403          *    forked CDRs.
2404          *  * If no one handled it, the last CDR in the chain. This would occur if
2405          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2406          *    to make pairings with everyone in the bridge.
2407          */
2408         if (!handled_cdr) {
2409                 handled_cdr = cdr->last;
2410         }
2411         handle_bridge_pairings(handled_cdr, bridge);
2412
2413         ao2_link(active_cdrs_by_bridge, cdr);
2414         ao2_unlock(cdr);
2415 }
2416
2417 struct ast_cdr_config *ast_cdr_get_config(void)
2418 {
2419         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2420         ao2_ref(mod_cfg->general, +1);
2421         return mod_cfg->general;
2422 }
2423
2424 void ast_cdr_set_config(struct ast_cdr_config *config)
2425 {
2426         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2427         ao2_cleanup(mod_cfg->general);
2428         mod_cfg->general = config;
2429         ao2_ref(mod_cfg->general, +1);
2430 }
2431
2432 int ast_cdr_is_enabled(void)
2433 {
2434         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2435         return ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED);
2436 }
2437
2438 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2439 {
2440         struct cdr_beitem *i = NULL;
2441
2442         if (!name)
2443                 return -1;
2444
2445         if (!be) {
2446                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2447                 return -1;
2448         }
2449
2450         AST_RWLIST_WRLOCK(&be_list);
2451         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2452                 if (!strcasecmp(name, i->name)) {
2453                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2454                         AST_RWLIST_UNLOCK(&be_list);
2455                         return -1;
2456                 }
2457         }
2458
2459         if (!(i = ast_calloc(1, sizeof(*i))))
2460                 return -1;
2461
2462         i->be = be;
2463         ast_copy_string(i->name, name, sizeof(i->name));
2464         ast_copy_string(i->desc, desc, sizeof(i->desc));
2465
2466         AST_RWLIST_INSERT_HEAD(&be_list, i, list);
2467         AST_RWLIST_UNLOCK(&be_list);
2468
2469         return 0;
2470 }
2471
2472 void ast_cdr_unregister(const char *name)
2473 {
2474         struct cdr_beitem *i = NULL;
2475
2476         AST_RWLIST_WRLOCK(&be_list);
2477         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&be_list, i, list) {
2478                 if (!strcasecmp(name, i->name)) {
2479                         AST_RWLIST_REMOVE_CURRENT(list);
2480                         break;
2481                 }
2482         }
2483         AST_RWLIST_TRAVERSE_SAFE_END;
2484         AST_RWLIST_UNLOCK(&be_list);
2485
2486         if (i) {
2487                 ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2488                 ast_free(i);
2489         }
2490 }
2491
2492 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2493 {
2494         struct ast_cdr *newcdr;
2495
2496         if (!cdr) {
2497                 return NULL;
2498         }
2499         newcdr = ast_cdr_alloc();
2500         if (!newcdr) {
2501                 return NULL;
2502         }
2503
2504         memcpy(newcdr, cdr, sizeof(*newcdr));
2505         memset(&newcdr->varshead, 0, sizeof(newcdr->varshead));
2506         copy_variables(&newcdr->varshead, &cdr->varshead);
2507         newcdr->next = NULL;
2508
2509         return newcdr;
2510 }
2511
2512 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2513 {
2514         struct ast_var_t *variables;
2515         struct varshead *headp = &cdr->varshead;
2516
2517         if (ast_strlen_zero(name)) {
2518                 return NULL;
2519         }
2520
2521         AST_LIST_TRAVERSE(headp, variables, entries) {
2522                 if (!strcasecmp(name, ast_var_name(variables))) {
2523                         return ast_var_value(variables);
2524                 }
2525         }
2526
2527         return '\0';
2528 }
2529
2530 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
2531 {
2532         if (fmt == NULL) {      /* raw mode */
2533                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
2534         } else {
2535                 if (when.tv_sec) {
2536                         struct ast_tm tm;
2537
2538                         ast_localtime(&when, &tm, NULL);
2539                         ast_strftime(buf, bufsize, fmt, &tm);
2540                 }
2541         }
2542 }
2543
2544 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
2545 {
2546         const char *fmt = "%Y-%m-%d %T";
2547         const char *varbuf;
2548
2549         if (!cdr) {
2550                 return;
2551         }
2552
2553         *ret = NULL;
2554
2555         if (!strcasecmp(name, "clid")) {
2556                 ast_copy_string(workspace, cdr->clid, workspacelen);
2557         } else if (!strcasecmp(name, "src")) {
2558                 ast_copy_string(workspace, cdr->src, workspacelen);
2559         } else if (!strcasecmp(name, "dst")) {
2560                 ast_copy_string(workspace, cdr->dst, workspacelen);
2561         } else if (!strcasecmp(name, "dcontext")) {
2562                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
2563         } else if (!strcasecmp(name, "channel")) {
2564                 ast_copy_string(workspace, cdr->channel, workspacelen);
2565         } else if (!strcasecmp(name, "dstchannel")) {
2566                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
2567         } else if (!strcasecmp(name, "lastapp")) {
2568                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
2569         } else if (!strcasecmp(name, "lastdata")) {
2570                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
2571         } else if (!strcasecmp(name, "start")) {
2572                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
2573         } else if (!strcasecmp(name, "answer")) {
2574                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
2575         } else if (!strcasecmp(name, "end")) {
2576                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
2577         } else if (!strcasecmp(name, "duration")) {
2578                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
2579         } else if (!strcasecmp(name, "billsec")) {
2580                 snprintf(workspace, workspacelen, "%ld", (cdr->billsec || !ast_tvzero(cdr->end) || ast_tvzero(cdr->answer)) ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
2581         } else if (!strcasecmp(name, "disposition")) {
2582                 if (raw) {
2583                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
2584                 } else {
2585                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
2586                 }
2587         } else if (!strcasecmp(name, "amaflags")) {
2588                 if (raw) {
2589                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
2590                 } else {
2591                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
2592                 }
2593         } else if (!strcasecmp(name, "accountcode")) {
2594                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
2595         } else if (!strcasecmp(name, "peeraccount")) {
2596                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
2597         } else if (!strcasecmp(name, "uniqueid")) {
2598                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
2599         } else if (!strcasecmp(name, "linkedid")) {
2600                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
2601         } else if (!strcasecmp(name, "userfield")) {
2602                 ast_copy_string(workspace, cdr->userfield, workspacelen);
2603         } else if (!strcasecmp(name, "sequence")) {
2604                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
2605         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
2606                 ast_copy_string(workspace, varbuf, workspacelen);
2607         } else {
2608                 workspace[0] = '\0';
2609         }
2610
2611         if (!ast_strlen_zero(workspace)) {
2612                 *ret = workspace;
2613         }
2614 }
2615
2616 /*
2617  * \internal
2618  * \brief Callback that finds all CDRs that reference a particular channel
2619  */
2620 static int cdr_object_select_all_by_channel_cb(void *obj, void *arg, int flags)
2621 {
2622         struct cdr_object *cdr = obj;
2623         const char *name = arg;
2624         if (!(flags & OBJ_KEY)) {
2625                 return 0;
2626         }
2627         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
2628                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
2629                 return CMP_MATCH;
2630         }
2631         return 0;
2632 }
2633
2634 /* Read Only CDR variables */
2635 static const char * const cdr_readonly_vars[] = { "clid", "src", "dst", "dcontext", "channel", "dstchannel",
2636                                                   "lastapp", "lastdata", "start", "answer", "end", "duration",
2637                                                   "billsec", "disposition", "amaflags", "accountcode", "uniqueid", "linkedid",
2638                                                   "userfield", "sequence", NULL };
2639
2640 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
2641 {
2642         struct cdr_object *cdr;
2643         struct cdr_object *it_cdr;
2644         struct ao2_iterator *it_cdrs;
2645         char *arg = ast_strdupa(channel_name);
2646         int x;
2647
2648         for (x = 0; cdr_readonly_vars[x]; x++) {
2649                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
2650                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
2651                         return -1;
2652                 }
2653         }
2654
2655         it_cdrs = ao2_callback(active_cdrs_by_channel, OBJ_MULTIPLE | OBJ_KEY, cdr_object_select_all_by_channel_cb, arg);
2656         if (!it_cdrs) {
2657                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
2658                 return -1;
2659         }
2660
2661         while ((cdr = ao2_iterator_next(it_cdrs))) {
2662                 ao2_lock(cdr);
2663                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2664                         struct varshead *headp = NULL;
2665                         if (it_cdr->fn_table == &finalized_state_fn_table) {
2666                                 continue;
2667                         }
2668                         if (!strcmp(channel_name, it_cdr->party_a.snapshot->name)) {
2669                                 headp = &it_cdr->party_a.variables;
2670                         } else if (it_cdr->party_b.snapshot && !strcmp(channel_name, it_cdr->party_b.snapshot->name)) {
2671                                 headp = &it_cdr->party_b.variables;
2672                         }
2673                         if (headp) {
2674                                 set_variable(headp, name, value);
2675                         }
2676                 }
2677                 ao2_unlock(cdr);
2678                 ao2_ref(cdr, -1);
2679         }
2680         ao2_iterator_destroy(it_cdrs);
2681
2682         return 0;
2683 }
2684
2685 /*!
2686  * \brief Format a variable on a \ref cdr_object
2687  */
2688 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
2689 {
2690         struct ast_var_t *variable;
2691
2692         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
2693                 if (!strcasecmp(name, ast_var_name(variable))) {
2694                         ast_copy_string(value, ast_var_value(variable), length);
2695                         return;
2696                 }
2697         }
2698
2699         *value = '\0';
2700 }
2701
2702 /*!
2703  * \brief Format one of the standard properties on a \ref cdr_object
2704  */
2705 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
2706 {
2707         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
2708         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
2709
2710         if (!strcasecmp(name, "clid")) {
2711                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
2712         } else if (!strcasecmp(name, "src")) {
2713                 ast_copy_string(value, party_a->caller_number, length);
2714         } else if (!strcasecmp(name, "dst")) {
2715                 ast_copy_string(value, party_a->exten, length);
2716         } else if (!strcasecmp(name, "dcontext")) {
2717                 ast_copy_string(value, party_a->context, length);
2718         } else if (!strcasecmp(name, "channel")) {
2719                 ast_copy_string(value, party_a->name, length);
2720         } else if (!strcasecmp(name, "dstchannel")) {
2721                 if (party_b) {
2722                         ast_copy_string(value, party_b->name, length);
2723                 } else {
2724                         ast_copy_string(value, "", length);
2725                 }
2726         } else if (!strcasecmp(name, "lastapp")) {
2727                 ast_copy_string(value, party_a->appl, length);
2728         } else if (!strcasecmp(name, "lastdata")) {
2729                 ast_copy_string(value, party_a->data, length);
2730         } else if (!strcasecmp(name, "start")) {
2731                 cdr_get_tv(cdr_obj->start, NULL, value, length);
2732         } else if (!strcasecmp(name, "answer")) {
2733                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
2734         } else if (!strcasecmp(name, "end")) {
2735                 cdr_get_tv(cdr_obj->end, NULL, value, length);
2736         } else if (!strcasecmp(name, "duration")) {
2737                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
2738         } else if (!strcasecmp(name, "billsec")) {
2739                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
2740         } else if (!strcasecmp(name, "disposition")) {
2741                 snprintf(value, length, "%d", cdr_obj->disposition);
2742         } else if (!strcasecmp(name, "amaflags")) {
2743                 snprintf(value, length, "%d", party_a->amaflags);
2744         } else if (!strcasecmp(name, "accountcode")) {
2745                 ast_copy_string(value, party_a->accountcode, length);
2746         } else if (!strcasecmp(name, "peeraccount")) {
2747                 if (party_b) {
2748                         ast_copy_string(value, party_b->accountcode, length);
2749                 } else {
2750                         ast_copy_string(value, "", length);
2751                 }
2752         } else if (!strcasecmp(name, "uniqueid")) {
2753                 ast_copy_string(value, party_a->uniqueid, length);
2754         } else if (!strcasecmp(name, "linkedid")) {
2755                 ast_copy_string(value, cdr_obj->linkedid, length);
2756         } else if (!strcasecmp(name, "userfield")) {
2757                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
2758         } else if (!strcasecmp(name, "sequence")) {
2759                 snprintf(value, length, "%d", cdr_obj->sequence);
2760         } else {
2761                 return 1;
2762         }
2763
2764         return 0;
2765 }
2766
2767 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
2768 {
2769         RAII_VAR(struct cdr_object *, cdr,
2770                 ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
2771                 ao2_cleanup);
2772         struct cdr_object *cdr_obj;
2773
2774         if (!cdr) {
2775                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
2776                 return 1;
2777         }
2778
2779         if (ast_strlen_zero(name)) {
2780                 return 1;
2781         }
2782
2783         ao2_lock(cdr);
2784
2785         cdr_obj = cdr->last;
2786
2787         if (cdr_object_format_property(cdr_obj, name, value, length)) {
2788                 /* Property failed; attempt variable */
2789                 cdr_object_format_var_internal(cdr_obj, name, value, length);
2790         }
2791         ao2_unlock(cdr);
2792
2793         return 0;
2794 }
2795
2796 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
2797 {
2798         RAII_VAR(struct cdr_object *, cdr,
2799                 ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
2800                 ao2_cleanup);
2801         struct cdr_object *it_cdr;
2802         struct ast_var_t *variable;
2803         const char *var;
2804         RAII_VAR(char *, workspace, ast_malloc(256), ast_free);
2805         int total = 0, x = 0, i;
2806
2807         if (!workspace) {
2808                 return 1;
2809         }
2810
2811         if (!cdr) {
2812                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
2813                 return 1;
2814         }
2815
2816         ast_str_reset(*buf);
2817
2818         ao2_lock(cdr);
2819         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2820                 if (++x > 1)
2821                         ast_str_append(buf, 0, "\n");
2822
2823                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
2824                         if (!(var = ast_var_name(variable))) {
2825                                 continue;
2826                         }
2827
2828                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
2829                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
2830                                 break;
2831                         }
2832
2833                         total++;
2834                 }
2835
2836                 for (i = 0; cdr_readonly_vars[i]; i++) {
2837                         /* null out the workspace, because the cdr_get_tv() won't write anything if time is NULL, so you get old vals */
2838                         workspace[0] = 0;
2839                         cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace));
2840
2841                         if (!ast_strlen_zero(workspace)
2842                                 && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
2843                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
2844                                 break;
2845                         }
2846                         total++;
2847                 }
2848         }
2849
2850         return total;
2851 }
2852
2853 void ast_cdr_free(struct ast_cdr *cdr)
2854 {
2855         while (cdr) {
2856                 struct ast_cdr *next = cdr->next;
2857
2858                 free_variables(&cdr->varshead);
2859                 ast_free(cdr);
2860                 cdr = next;
2861         }
2862 }
2863
2864 struct ast_cdr *ast_cdr_alloc(void)
2865 {
2866         struct ast_cdr *x;
2867
2868         x = ast_calloc(1, sizeof(*x));
2869         return x;
2870 }
2871
2872 const char *ast_cdr_disp2str(int disposition)
2873 {
2874         switch (disposition) {
2875         case AST_CDR_NULL:
2876                 return "NO ANSWER"; /* by default, for backward compatibility */
2877         case AST_CDR_NOANSWER:
2878                 return "NO ANSWER";
2879         case AST_CDR_FAILED:
2880                 return "FAILED";
2881         case AST_CDR_BUSY:
2882                 return "BUSY";
2883         case AST_CDR_ANSWERED:
2884                 return "ANSWERED";
2885         case AST_CDR_CONGESTION:
2886                 return "CONGESTION";
2887         }
2888         return "UNKNOWN";
2889 }
2890
2891 struct party_b_userfield_update {
2892         const char *channel_name;
2893         const char *userfield;
2894 };
2895
2896 /*! \brief Callback used to update the userfield on Party B on all CDRs */
2897 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, int flags)
2898 {
2899         struct cdr_object *cdr = obj;
2900         struct party_b_userfield_update *info = arg;
2901         struct cdr_object *it_cdr;
2902         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2903                 if (it_cdr->fn_table == &finalized_state_fn_table) {
2904                         continue;
2905                 }
2906                 if (it_cdr->party_b.snapshot
2907                         && !strcmp(it_cdr->party_b.snapshot->name, info->channel_name)) {
2908                         strcpy(it_cdr->party_b.userfield, info->userfield);
2909                 }
2910         }
2911         return 0;
2912 }
2913
2914 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
2915 {
2916         RAII_VAR(struct cdr_object *, cdr,
2917                         ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
2918                         ao2_cleanup);
2919         struct party_b_userfield_update party_b_info = {
2920                         .channel_name = channel_name,
2921                         .userfield = userfield,
2922         };
2923         struct cdr_object *it_cdr;
2924
2925         /* Handle Party A */
2926         if (cdr) {
2927                 ao2_lock(cdr);
2928                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2929                         if (it_cdr->fn_table == &finalized_state_fn_table) {
2930                                 continue;
2931                         }
2932                         strcpy(it_cdr->party_a.userfield, userfield);
2933                 }
2934                 ao2_unlock(cdr);
2935         }
2936
2937         /* Handle Party B */
2938         ao2_callback(active_cdrs_by_channel, OBJ_NODATA,
2939                         cdr_object_update_party_b_userfield_cb,
2940                         &party_b_info);
2941
2942 }
2943
2944 static void post_cdr(struct ast_cdr *cdr)
2945 {
2946         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2947         struct cdr_beitem *i;
2948
2949         for (; cdr ; cdr = cdr->next) {
2950                 /* For people, who don't want to see unanswered single-channel events */
2951                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
2952                                 cdr->disposition < AST_CDR_ANSWERED &&
2953                                 (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
2954                         continue;
2955                 }
2956
2957                 if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
2958                         continue;
2959                 }
2960                 AST_RWLIST_RDLOCK(&be_list);
2961                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
2962                         i->be(cdr);
2963                 }
2964                 AST_RWLIST_UNLOCK(&be_list);
2965         }
2966 }
2967
2968 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
2969 {
2970         RAII_VAR(struct cdr_object *, cdr,
2971                         ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
2972                         ao2_cleanup);
2973         struct cdr_object *it_cdr;
2974
2975         if (!cdr) {
2976                 return -1;
2977         }
2978
2979         ao2_lock(cdr);
2980         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2981                 if (it_cdr->fn_table == &finalized_state_fn_table) {
2982                         continue;
2983                 }
2984                 ast_set_flag(&it_cdr->flags, option);
2985         }
2986         ao2_unlock(cdr);
2987
2988         return 0;
2989 }
2990
2991 int ast_cdr_clear_property(const char *channel_name, enum ast_cdr_options option)
2992 {
2993         RAII_VAR(struct cdr_object *, cdr,
2994                         ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
2995                         ao2_cleanup);
2996         struct cdr_object *it_cdr;
2997
2998         if (!cdr) {
2999                 return -1;
3000         }
3001
3002         ao2_lock(cdr);
3003         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3004                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3005                         continue;
3006                 }
3007                 ast_clear_flag(&it_cdr->flags, option);
3008         }
3009         ao2_unlock(cdr);
3010
3011         return 0;
3012 }
3013
3014 int ast_cdr_reset(const char *channel_name, struct ast_flags *options)
3015 {
3016         RAII_VAR(struct cdr_object *, cdr,
3017                         ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
3018                         ao2_cleanup);
3019         struct ast_var_t *vardata;
3020         struct cdr_object *it_cdr;
3021
3022         if (!cdr) {
3023                 return -1;
3024         }
3025
3026         ao2_lock(cdr);
3027         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3028                 /* clear variables */
3029                 if (!ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3030                         while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_a.variables, entries))) {
3031                                 ast_var_delete(vardata);
3032                         }
3033                         if (cdr->party_b.snapshot) {
3034                                 while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_b.variables, entries))) {
3035                                         ast_var_delete(vardata);
3036                                 }
3037                         }
3038                 }
3039
3040                 /* Reset to initial state */
3041                 memset(&it_cdr->start, 0, sizeof(it_cdr->start));
3042                 memset(&it_cdr->end, 0, sizeof(it_cdr->end));
3043                 memset(&it_cdr->answer, 0, sizeof(it_cdr->answer));
3044                 it_cdr->start = ast_tvnow();
3045                 cdr_object_check_party_a_answer(it_cdr);
3046         }
3047         ao2_unlock(cdr);
3048
3049         return 0;
3050 }
3051
3052 int ast_cdr_fork(const char *channel_name, struct ast_flags *options)
3053 {
3054         RAII_VAR(struct cdr_object *, cdr,
3055                         ao2_find(active_cdrs_by_channel, channel_name, OBJ_KEY),
3056                         ao2_cleanup);
3057         struct cdr_object *new_cdr;
3058         struct cdr_object *it_cdr;
3059         struct cdr_object *cdr_obj;
3060
3061         if (!cdr) {
3062                 return -1;
3063         }
3064
3065         {
3066                 SCOPED_AO2LOCK(lock, cdr);
3067                 cdr_obj = cdr->last;
3068                 if (cdr_obj->fn_table == &finalized_state_fn_table) {
3069                         /* If the last CDR in the chain is finalized, don't allow a fork -
3070                          * things are already dying at this point
3071                          */
3072                         ast_log(AST_LOG_ERROR, "FARK\n");
3073                         return -1;
3074                 }
3075
3076                 /* Copy over the basic CDR information. The Party A information is
3077                  * copied over automatically as part of the append
3078                  */
3079                 ast_debug(1, "Forking CDR for channel %s\n", cdr->party_a.snapshot->name);
3080                 new_cdr = cdr_object_create_and_append(cdr);
3081                 if (!new_cdr) {
3082                         return -1;
3083                 }
3084                 new_cdr->fn_table = cdr_obj->fn_table;
3085                 ast_string_field_set(new_cdr, bridge, cdr->bridge);
3086                 new_cdr->flags = cdr->flags;
3087
3088                 /* If there's a Party B, copy it over as well */
3089                 if (cdr_obj->party_b.snapshot) {
3090                         new_cdr->party_b.snapshot = cdr_obj->party_b.snapshot;
3091                         ao2_ref(new_cdr->party_b.snapshot, +1);
3092                         strcpy(new_cdr->party_b.userfield, cdr_obj->party_b.userfield);
3093                         new_cdr->party_b.flags = cdr_obj->party_b.flags;
3094                         if (ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3095                                 copy_variables(&new_cdr->party_b.variables, &cdr_obj->party_b.variables);
3096                         }
3097                 }
3098                 new_cdr->start = cdr_obj->start;
3099                 new_cdr->answer = cdr_obj->answer;
3100
3101                 /* Modify the times based on the flags passed in */
3102                 if (ast_test_flag(options, AST_CDR_FLAG_SET_ANSWER)
3103                                 && new_cdr->party_a.snapshot->state == AST_STATE_UP) {
3104                         new_cdr->answer = ast_tvnow();
3105                 }
3106                 if (ast_test_flag(options, AST_CDR_FLAG_RESET)) {
3107                         new_cdr->answer = ast_tvnow();
3108                         new_cdr->start = ast_tvnow();
3109                 }
3110
3111                 /* Create and append, by default, copies over the variables */
3112                 if (!ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3113                         free_variables(&new_cdr->party_a.variables);
3114                 }
3115
3116                 /* Finalize any current CDRs */
3117                 if (ast_test_flag(options, AST_CDR_FLAG_FINALIZE)) {
3118                         for (it_cdr = cdr; it_cdr != new_cdr; it_cdr = it_cdr->next) {
3119                                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3120                                         continue;
3121                                 }
3122                                 /* Force finalization on the CDR. This will bypass any checks for
3123                                  * end before 'h' extension.
3124                                  */
3125                                 cdr_object_finalize(it_cdr);
3126                                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
3127                         }
3128                 }
3129         }
3130
3131         return 0;
3132 }
3133
3134 /*! \note Don't call without cdr_batch_lock */
3135 static void reset_batch(void)
3136 {
3137         batch->size = 0;
3138         batch->head = NULL;
3139         batch->tail = NULL;
3140 }
3141
3142 /*! \note Don't call without cdr_batch_lock */
3143 static int init_batch(void)
3144 {
3145         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
3146         if (!(batch = ast_malloc(sizeof(*batch))))
3147                 return -1;
3148
3149         reset_batch();
3150
3151         return 0;
3152 }
3153
3154 static void *do_batch_backend_process(void *data)
3155 {
3156         struct cdr_batch_item *processeditem;
3157         struct cdr_batch_item *batchitem = data;
3158
3159         /* Push each CDR into storage mechanism(s) and free all the memory */
3160         while (batchitem) {
3161                 post_cdr(batchitem->cdr);
3162                 ast_cdr_free(batchitem->cdr);
3163                 processeditem = batchitem;
3164                 batchitem = batchitem->next;
3165                 ast_free(processeditem);
3166         }
3167
3168         return NULL;
3169 }
3170
3171 static void cdr_submit_batch(int do_shutdown)
3172 {
3173         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3174         struct cdr_batch_item *oldbatchitems = NULL;
3175         pthread_t batch_post_thread = AST_PTHREADT_NULL;
3176
3177         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
3178         if (!batch || !batch->head) {
3179                 return;
3180         }
3181
3182         /* move the old CDRs aside, and prepare a new CDR batch */
3183         ast_mutex_lock(&cdr_batch_lock);
3184         oldbatchitems = batch->head;
3185         reset_batch();
3186         ast_mutex_unlock(&cdr_batch_lock);
3187
3188         /* if configured, spawn a new thread to post these CDRs,
3189            also try to save as much as possible if we are shutting down safely */
3190         if (ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY) || do_shutdown) {
3191                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
3192                 do_batch_backend_process(oldbatchitems);
3193         } else {
3194                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
3195                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
3196                         do_batch_backend_process(oldbatchitems);
3197                 } else {
3198                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
3199                 }
3200         }
3201 }
3202
3203 static int submit_scheduled_batch(const void *data)
3204 {
3205         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3206         cdr_submit_batch(0);
3207         /* manually reschedule from this point in time */
3208
3209         ast_mutex_lock(&cdr_sched_lock);
3210         cdr_sched = ast_sched_add(sched, mod_cfg->general->batch_settings.size * 1000, submit_scheduled_batch, NULL);
3211         ast_mutex_unlock(&cdr_sched_lock);
3212         /* returning zero so the scheduler does not automatically reschedule */
3213         return 0;
3214 }
3215
3216 /*! Do not hold the batch lock while calling this function */
3217 static void submit_unscheduled_batch(void)
3218 {
3219         /* Prevent two deletes from happening at the same time */
3220         ast_mutex_lock(&cdr_sched_lock);
3221         /* this is okay since we are not being called from within the scheduler */
3222         AST_SCHED_DEL(sched, cdr_sched);
3223         /* schedule the submission to occur ASAP (1 ms) */
3224         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
3225         ast_mutex_unlock(&cdr_sched_lock);
3226
3227         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
3228         ast_mutex_lock(&cdr_pending_lock);
3229         ast_cond_signal(&cdr_pending_cond);
3230         ast_mutex_unlock(&cdr_pending_lock);
3231 }
3232
3233 static void cdr_detach(struct ast_cdr *cdr)
3234 {
3235         struct cdr_batch_item *newtail;
3236         int curr;
3237         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3238         int submit_batch = 0;
3239
3240         if (!cdr) {
3241                 return;
3242         }
3243
3244         /* maybe they disabled CDR stuff completely, so just drop it */
3245         if (!ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3246                 ast_debug(1, "Dropping CDR !\n");
3247                 ast_cdr_free(cdr);
3248                 return;
3249         }
3250
3251         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
3252         if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3253                 post_cdr(cdr);
3254                 ast_cdr_free(cdr);
3255                 return;
3256         }
3257
3258         /* otherwise, each CDR gets put into a batch list (at the end) */
3259         ast_debug(1, "CDR detaching from this thread\n");
3260
3261         /* we'll need a new tail for every CDR */
3262         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
3263                 post_cdr(cdr);
3264                 ast_cdr_free(cdr);
3265                 return;
3266         }
3267
3268         /* don't traverse a whole list (just keep track of the tail) */
3269         ast_mutex_lock(&cdr_batch_lock);
3270         if (!batch)
3271                 init_batch();
3272         if (!batch->head) {
3273                 /* new batch is empty, so point the head at the new tail */
3274                 batch->head = newtail;
3275         } else {
3276                 /* already got a batch with something in it, so just append a new tail */
3277                 batch->tail->next = newtail;
3278         }
3279         newtail->cdr = cdr;
3280         batch->tail = newtail;
3281         curr = batch->size++;
3282
3283         /* if we have enough stuff to post, then do it */
3284         if (curr >= (mod_cfg->general->batch_settings.size - 1)) {
3285                 submit_batch = 1;
3286         }
3287         ast_mutex_unlock(&cdr_batch_lock);
3288
3289         /* Don't call submit_unscheduled_batch with the cdr_batch_lock held */
3290         if (submit_batch) {
3291                 submit_unscheduled_batch();
3292         }
3293 }
3294
3295 static void *do_cdr(void *data)
3296 {
3297         struct timespec timeout;
3298         int schedms;
3299         int numevents = 0;
3300
3301         for (;;) {
3302                 struct timeval now;
3303                 schedms = ast_sched_wait(sched);
3304                 /* this shouldn't happen, but provide a 1 second default just in case */
3305                 if (schedms <= 0)
3306                         schedms = 1000;
3307                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
3308                 timeout.tv_sec = now.tv_sec;
3309                 timeout.tv_nsec = now.tv_usec * 1000;
3310                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
3311                 ast_mutex_lock(&cdr_pending_lock);
3312                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
3313                 numevents = ast_sched_runq(sched);
3314                 ast_mutex_unlock(&cdr_pending_lock);
3315                 ast_debug(2, "Processed %d scheduled CDR batches from the run queue\n", numevents);
3316         }
3317
3318         return NULL;
3319 }
3320
3321 static char *handle_cli_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3322 {
3323         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3324
3325         switch (cmd) {
3326         case CLI_INIT:
3327                 e->command = "cdr set debug [on|off]";
3328                 e->usage = "Enable or disable extra debugging in the CDR Engine";
3329                 return NULL;
3330         case CLI_GENERATE:
3331                 return NULL;
3332         }
3333
3334         if (a->argc != 4) {
3335                 return CLI_SHOWUSAGE;
3336         }
3337
3338         if (!strcmp(a->argv[3], "on") && !ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3339                 ast_set_flag(&mod_cfg->general->settings, CDR_DEBUG);
3340                 ast_cli(a->fd, "CDR debugging enabled\n");
3341         } else if (!strcmp(a->argv[3], "off") && ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3342                 ast_clear_flag(&mod_cfg->general->settings, CDR_DEBUG);
3343                 ast_cli(a->fd, "CDR debugging disabled\n");
3344         }
3345
3346         return CLI_SUCCESS;
3347 }
3348
3349 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3350 {
3351         struct cdr_beitem *beitem = NULL;
3352         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3353         int cnt = 0;
3354         long nextbatchtime = 0;
3355
3356         switch (cmd) {
3357         case CLI_INIT:
3358                 e->command = "cdr show status";
3359                 e->usage =
3360                         "Usage: cdr show status\n"
3361                         "       Displays the Call Detail Record engine system status.\n";
3362                 return NULL;
3363         case CLI_GENERATE:
3364                 return NULL;
3365         }
3366
3367         if (a->argc > 3)
3368                 return CLI_SHOWUSAGE;
3369
3370         ast_cli(a->fd, "\n");
3371         ast_cli(a->fd, "Call Detail Record (CDR) settings\n");
3372         ast_cli(a->fd, "----------------------------------\n");
3373         ast_cli(a->fd, "  Logging:                    %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED) ? "Enabled" : "Disabled");
3374         ast_cli(a->fd, "  Mode:                       %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE) ? "Batch" : "Simple");
3375         if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3376                 ast_cli(a->fd, "  Log unanswered calls:       %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) ? "Yes" : "No");
3377                 ast_cli(a->fd, "  Log congestion:             %s\n\n", ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION) ? "Yes" : "No");
3378                 if (ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3379                         ast_cli(a->fd, "* Batch Mode Settings\n");
3380                         ast_cli(a->fd, "  -------------------\n");
3381                         if (batch)
3382                                 cnt = batch->size;
3383                         if (cdr_sched > -1)
3384                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
3385                         ast_cli(a->fd, "  Safe shutdown:              %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SAFE_SHUTDOWN) ? "Enabled" : "Disabled");
3386                         ast_cli(a->fd, "  Threading model:            %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY) ? "Scheduler only" : "Scheduler plus separate threads");
3387                         ast_cli(a->fd, "  Current batch size:         %d record%s\n", cnt, ESS(cnt));
3388                         ast_cli(a->fd, "  Maximum batch size:         %d record%s\n", mod_cfg->general->batch_settings.size, ESS(mod_cfg->general->batch_settings.size));
3389                         ast_cli(a->fd, "  Maximum batch time:         %d second%s\n", mod_cfg->general->batch_settings.time, ESS(mod_cfg->general->batch_settings.time));
3390                         ast_cli(a->fd, "  Next batch processing time: %ld second%s\n\n", nextbatchtime, ESS(nextbatchtime));
3391                 }
3392                 ast_cli(a->fd, "* Registered Backends\n");
3393                 ast_cli(a->fd, "  -------------------\n");
3394                 AST_RWLIST_RDLOCK(&be_list);
3395                 if (AST_RWLIST_EMPTY(&be_list)) {
3396                         ast_cli(a->fd, "    (none)\n");
3397                 } else {
3398                         AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
3399                                 ast_cli(a->fd, "    %s\n", beitem->name);
3400                         }
3401                 }
3402                 AST_RWLIST_UNLOCK(&be_list);
3403                 ast_cli(a->fd, "\n");
3404         }
3405
3406         return CLI_SUCCESS;
3407 }
3408
3409 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3410 {
3411         switch (cmd) {
3412         case CLI_INIT:
3413                 e->command = "cdr submit";
3414                 e->usage =
3415                         "Usage: cdr submit\n"
3416                         "       Posts all pending batched CDR data to the configured CDR backend engine modules.\n";
3417                 return NULL;
3418         case CLI_GENERATE:
3419                 return NULL;
3420         }
3421         if (a->argc > 2)
3422                 return CLI_SHOWUSAGE;
3423
3424         submit_unscheduled_batch();
3425         ast_cli(a->fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
3426
3427         return CLI_SUCCESS;
3428 }
3429
3430 static struct ast_cli_entry cli_submit = AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data");
3431 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CDR status");
3432 static struct ast_cli_entry cli_debug = AST_CLI_DEFINE(handle_cli_debug, "Enable debugging");
3433
3434
3435 /*!
3436  * \brief This dispatches *all* \ref cdr_objects. It should only be used during
3437  * shutdown, so that we get billing records for everything that we can.
3438  */
3439 static int cdr_object_dispatch_all_cb(void *obj, void *arg, int flags)
3440 {
3441         struct cdr_object *cdr = obj;
3442         struct cdr_object *it_cdr;
3443
3444         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3445                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
3446         }
3447         cdr_object_dispatch(cdr);
3448
3449         return 0;
3450 }
3451
3452 static void finalize_batch_mode(void)
3453 {
3454         if (cdr_thread == AST_PTHREADT_NULL) {
3455                 return;
3456         }
3457         /* wake up the thread so it will exit */
3458         pthread_cancel(cdr_thread);
3459         pthread_kill(cdr_thread, SIGURG);
3460         pthread_join(cdr_thread, NULL);
3461         cdr_thread = AST_PTHREADT_NULL;
3462         ast_cond_destroy(&cdr_pending_cond);
3463         ast_cli_unregister(&cli_submit);
3464         ast_cdr_engine_term();
3465 }
3466
3467 static int process_config(int reload)
3468 {
3469         RAII_VAR(struct module_config *, mod_cfg, module_config_alloc(), ao2_cleanup);
3470
3471         if (!reload) {
3472                 if (aco_info_init(&cfg_info)) {
3473                         return 1;
3474                 }
3475
3476                 aco_option_register(&cfg_info, "enable", ACO_EXACT, general_options, DEFAULT_ENABLED, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_ENABLED);
3477                 aco_option_register(&cfg_info, "debug", ACO_EXACT, general_options, 0, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_DEBUG);
3478                 aco_option_register(&cfg_info, "unanswered", ACO_EXACT, general_options, DEFAULT_UNANSWERED, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_UNANSWERED);
3479                 aco_option_register(&cfg_info, "congestion", ACO_EXACT, general_options, 0, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_CONGESTION);
3480                 aco_option_register(&cfg_info, "batch", ACO_EXACT, general_options, DEFAULT_BATCHMODE, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_BATCHMODE);
3481                 aco_option_register(&cfg_info, "endbeforehexten", ACO_EXACT, general_options, DEFAULT_END_BEFORE_H_EXTEN, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_END_BEFORE_H_EXTEN);
3482                 aco_option_register(&cfg_info, "initiatedseconds", ACO_EXACT, general_options, DEFAULT_INITIATED_SECONDS, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_INITIATED_SECONDS);
3483                 aco_option_register(&cfg_info, "scheduleronly", ACO_EXACT, general_options, DEFAULT_BATCH_SCHEDULER_ONLY, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, batch_settings.settings), BATCH_MODE_SCHEDULER_ONLY);
3484                 aco_option_register(&cfg_info, "safeshutdown", ACO_EXACT, general_options, DEFAULT_BATCH_SAFE_SHUTDOWN, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, batch_settings.settings), BATCH_MODE_SAFE_SHUTDOWN);
3485                 aco_option_register(&cfg_info, "size", ACO_EXACT, general_options, DEFAULT_BATCH_SIZE, OPT_UINT_T, PARSE_IN_RANGE, FLDSET(struct ast_cdr_config, batch_settings.size), 0, MAX_BATCH_SIZE);
3486                 aco_option_register(&cfg_info, "time", ACO_EXACT, general_options, DEFAULT_BATCH_TIME, OPT_UINT_T, PARSE_IN_RANGE, FLDSET(struct ast_cdr_config, batch_settings.time), 0, MAX_BATCH_TIME);
3487         }
3488
3489         if (aco_process_config(&cfg_info, reload)) {
3490                 if (!mod_cfg) {
3491                         return 1;
3492                 }
3493                 /* If we couldn't process the configuration and this wasn't a reload,
3494                  * create a default config
3495                  */
3496                 if (!reload && !(aco_set_defaults(&general_option, "general", mod_cfg->general))) {
3497                         ast_log(LOG_NOTICE, "Failed to process CDR configuration; using defaults\n");
3498                         ao2_global_obj_replace(module_configs, mod_cfg);
3499                         return 0;
3500                 }
3501                 return 1;
3502         }
3503
3504         if (reload) {
3505                 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: CDR\r\nMessage: CDR subsystem reload requested\r\n");
3506         }
3507         return 0;
3508 }
3509
3510 static void cdr_engine_shutdown(void)
3511 {
3512         ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_dispatch_all_cb,
3513                 NULL);
3514         finalize_batch_mode();
3515         aco_info_destroy(&cfg_info);
3516         ast_cli_unregister(&cli_status);
3517         ast_cli_unregister(&cli_debug);
3518         ast_sched_context_destroy(sched);
3519         sched = NULL;
3520         ast_free(batch);
3521         batch = NULL;
3522
3523         ao2_ref(active_cdrs_by_channel, -1);
3524         ao2_ref(active_cdrs_by_bridge, -1);
3525 }
3526
3527 static void cdr_enable_batch_mode(struct ast_cdr_config *config)
3528 {
3529         SCOPED_LOCK(batch, &cdr_batch_lock, ast_mutex_lock, ast_mutex_unlock);
3530
3531         /* Only create the thread level portions once */
3532         if (cdr_thread == AST_PTHREADT_NULL) {
3533                 ast_cond_init(&cdr_pending_cond, NULL);
3534                 if (ast_pthread_create_background(&cdr_thread, NULL, do_cdr, NULL) < 0) {
3535                         ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
3536                         return;
3537                 }
3538                 ast_cli_register(&cli_submit);
3539         }
3540
3541         /* Kill the currently scheduled item */
3542         AST_SCHED_DEL(sched, cdr_sched);
3543         cdr_sched = ast_sched_add(sched, config->batch_settings.time * 1000, submit_scheduled_batch, NULL);
3544         ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %d or time %d seconds.\n",
3545                         config->batch_settings.size, config->batch_settings.time);
3546 }
3547
3548 int ast_cdr_engine_init(void)
3549 {
3550         RAII_VAR(struct module_config *, mod_cfg, NULL, ao2_cleanup);
3551
3552         if (process_config(0)) {
3553                 return -1;
3554         }
3555
3556         /* The prime here should be the same as the channel container */
3557         active_cdrs_by_channel = ao2_container_alloc(51, cdr_object_channel_hash_fn, cdr_object_channel_cmp_fn);
3558         if (!active_cdrs_by_channel) {
3559                 return -1;
3560         }
3561
3562         active_cdrs_by_bridge = ao2_container_alloc(51, cdr_object_bridge_hash_fn, cdr_object_bridge_cmp_fn);
3563         if (!active_cdrs_by_bridge) {
3564                 return -1;
3565         }
3566
3567         cdr_topic = stasis_topic_create("cdr_engine");
3568         if (!cdr_topic) {
3569                 return -1;
3570         }
3571
3572         channel_subscription = stasis_forward_all(stasis_caching_get_topic(ast_channel_topic_all_cached()), cdr_topic);
3573         if (!channel_subscription) {
3574                 return -1;
3575         }
3576         bridge_subscription = stasis_forward_all(stasis_caching_get_topic(ast_bridge_topic_all_cached()), cdr_topic);
3577         if (!bridge_subscription) {
3578                 return -1;
3579         }
3580         stasis_router = stasis_message_router_create(cdr_topic);
3581         if (!stasis_router) {
3582                 return -1;
3583         }
3584         stasis_message_router_add(stasis_router, stasis_cache_update_type(), handle_channel_cache_message, NULL);
3585         stasis_message_router_add(stasis_router, ast_channel_dial_type(), handle_dial_message, NULL);
3586         stasis_message_router_add(stasis_router, ast_channel_entered_bridge_type(), handle_bridge_enter_message, NULL);
3587         stasis_message_router_add(stasis_router, ast_channel_left_bridge_type(), handle_bridge_leave_message, NULL);
3588
3589         sched = ast_sched_context_create();
3590         if (!sched) {
3591                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
3592                 return -1;
3593         }
3594
3595         ast_cli_register(&cli_status);
3596         ast_cli_register(&cli_debug);
3597         ast_register_atexit(cdr_engine_shutdown);
3598
3599         mod_cfg = ao2_global_obj_ref(module_configs);
3600
3601         if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3602                 if (ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3603                         cdr_enable_batch_mode(mod_cfg->general);
3604                 } else {
3605                         ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
3606                 }
3607         } else {
3608                 ast_log(LOG_NOTICE, "CDR logging disabled.\n");
3609         }
3610
3611         return 0;
3612 }
3613
3614 void ast_cdr_engine_term(void)
3615 {
3616         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3617
3618         /* Since this is called explicitly during process shutdown, we might not have ever
3619          * been initialized. If so, the config object will be NULL.
3620          */
3621         if (!mod_cfg) {
3622                 return;
3623         }
3624         if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3625                 return;
3626         }
3627         cdr_submit_batch(ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SAFE_SHUTDOWN));
3628 }
3629
3630 int ast_cdr_engine_reload(void)
3631 {
3632         RAII_VAR(struct module_config *, old_mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3633         RAII_VAR(struct module_config *, mod_cfg, NULL, ao2_cleanup);
3634
3635         if (process_config(1)) {
3636                 return -1;
3637         }
3638
3639         mod_cfg = ao2_global_obj_ref(module_configs);
3640
3641         if (!ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED) ||
3642                         !(ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE))) {
3643                 /* If batch mode used to be enabled, finalize the batch */
3644                 if (ast_test_flag(&old_mod_cfg->general->settings, CDR_BATCHMODE)) {
3645                         finalize_batch_mode();
3646                 }
3647         }
3648
3649         if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3650                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3651                         ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
3652                 } else {
3653                         cdr_enable_batch_mode(mod_cfg->general);
3654                 }
3655         } else {
3656                 ast_log(LOG_NOTICE, "CDR logging disabled, data will be lost.\n");
3657         }
3658
3659         return 0;
3660 }
3661
3662