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