main/cdr: Set the end time on a CDR if endbeforehexten is Yes
[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_REGISTER_FILE()
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 and don't set an outgoing party.</synopsis>
102                                         <description><para>
103                                         Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
104                                         this to "yes" will make calls to extensions that don't answer and don't set a side B channel
105                                         (such as by using the Dial application) receive CDR log entries. If this option is set to
106                                         "no", then those log entries will not be created. Unanswered calls which get offered to an
107                                         outgoing line will always receive log entries regardless of this option, and that is the
108                                         intended behavior.
109                                         </para>
110                                         </description>
111                                 </configOption>
112                                 <configOption name="congestion">
113                                         <synopsis>Log congested calls.</synopsis>
114                                         <description><para>Define whether or not to log congested calls. Setting this to "yes" will
115                                         report each call that fails to complete due to congestion conditions.</para>
116                                         </description>
117                                 </configOption>
118                                 <configOption name="endbeforehexten">
119                                         <synopsis>Don't produce CDRs while executing hangup logic</synopsis>
120                                         <description>
121                                                 <para>As each CDR for a channel is finished, its end time is updated
122                                                 and the CDR is finalized. When a channel is hung up and hangup
123                                                 logic is present (in the form of a hangup handler or the
124                                                 <literal>h</literal> extension), a new CDR is generated for the
125                                                 channel. Any statistics are gathered from this new CDR. By enabling
126                                                 this option, no new CDR is created for the dialplan logic that is
127                                                 executed in <literal>h</literal> extensions or attached hangup handler
128                                                 subroutines. The default value is <literal>yes</literal>, indicating
129                                                 that a CDR will be generated during hangup logic.</para>
130                                         </description>
131                                 </configOption>
132                                 <configOption name="initiatedseconds">
133                                         <synopsis>Count microseconds for billsec purposes</synopsis>
134                                         <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
135                                         is simply the end time (hangup time) minus the answer time in seconds. Internally,
136                                         asterisk stores the time in terms of microseconds and seconds. By setting
137                                         initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
138                                         that were initiated (a sort of round up method). Technically, this is
139                                         when the microsecond part of the end time is greater than the microsecond
140                                         part of the answer time, then the billsec time is incremented one second.</para>
141                                         </description>
142                                 </configOption>
143                                 <configOption name="batch">
144                                         <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
145                                         <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
146                                         every call, the data will be stored in a buffer to help alleviate load on the
147                                         asterisk server.</para>
148                                         <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
149                                         i.e., software crash, power failure, kill -9, etc.</para>
150                                         </warning>
151                                         </description>
152                                 </configOption>
153                                 <configOption name="size">
154                                         <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
155                                         <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
156                                         them to the backend engines. batch must be set to <literal>yes</literal>.</para>
157                                         </description>
158                                 </configOption>
159                                 <configOption name="time">
160                                         <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
161                                         <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
162                                         backend engines. If this time limit is reached, then it will post the records, regardless of the value
163                                         defined for size. batch must be set to <literal>yes</literal>.</para>
164                                         <note><para>Time is expressed in seconds.</para></note>
165                                         </description>
166                                 </configOption>
167                                 <configOption name="scheduleronly">
168                                         <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
169                                         <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
170                                         records.  Posting can either occur inside the scheduler thread, or a new
171                                         thread can be spawned for the submission of every batch.  For small batches,
172                                         it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
173                                         For large batches, say anything over size=10, a new thread is recommended, so
174                                         set this to <literal>no</literal>.</para>
175                                         </description>
176                                 </configOption>
177                                 <configOption name="safeshutdown">
178                                         <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
179                                         <description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
180                                         you don't, then data will likely be lost.  You can always check the size of
181                                         the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
182                                         submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
183                                         </description>
184                                 </configOption>
185                         </configObject>
186                 </configFile>
187         </configInfo>
188  ***/
189
190
191 /* The prime here should be similar in size to the channel container. */
192 #ifdef LOW_MEMORY
193 #define NUM_CDR_BUCKETS 61
194 #else
195 #define NUM_CDR_BUCKETS 769
196 #endif
197
198 #define DEFAULT_ENABLED "1"
199 #define DEFAULT_BATCHMODE "0"
200 #define DEFAULT_UNANSWERED "0"
201 #define DEFAULT_CONGESTION "0"
202 #define DEFAULT_END_BEFORE_H_EXTEN "1"
203 #define DEFAULT_INITIATED_SECONDS "0"
204
205 #define DEFAULT_BATCH_SIZE "100"
206 #define MAX_BATCH_SIZE 1000
207 #define DEFAULT_BATCH_TIME "300"
208 #define MAX_BATCH_TIME 86400
209 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
210 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
211
212 #define CDR_DEBUG(mod_cfg, fmt, ...) \
213         do { \
214                 if (ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG)) { \
215                         ast_verbose((fmt), ##__VA_ARGS__); \
216                 } \
217         } while (0)
218
219 static void cdr_detach(struct ast_cdr *cdr);
220 static void cdr_submit_batch(int shutdown);
221 static int cdr_toggle_runtime_options(void);
222
223 /*! \brief The configuration settings for this module */
224 struct module_config {
225         struct ast_cdr_config *general;         /*< CDR global settings */
226 };
227
228 /*! \brief The container for the module configuration */
229 static AO2_GLOBAL_OBJ_STATIC(module_configs);
230
231 /*! \brief The type definition for general options */
232 static struct aco_type general_option = {
233         .type = ACO_GLOBAL,
234         .name = "general",
235         .item_offset = offsetof(struct module_config, general),
236         .category = "^general$",
237         .category_match = ACO_WHITELIST,
238 };
239
240 static void *module_config_alloc(void);
241 static void module_config_destructor(void *obj);
242
243 /*! \brief The file definition */
244 static struct aco_file module_file_conf = {
245         .filename = "cdr.conf",
246         .skip_category = "(^csv$|^custom$|^manager$|^odbc$|^pgsql$|^radius$|^sqlite$|^tds$|^mysql$)",
247         .types = ACO_TYPES(&general_option),
248 };
249
250 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
251         .files = ACO_FILES(&module_file_conf),
252 );
253
254 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
255
256 /*! \brief Dispose of a module config object */
257 static void module_config_destructor(void *obj)
258 {
259         struct module_config *cfg = obj;
260
261         if (!cfg) {
262                 return;
263         }
264         ao2_ref(cfg->general, -1);
265 }
266
267 /*! \brief Create a new module config object */
268 static void *module_config_alloc(void)
269 {
270         struct module_config *mod_cfg;
271         struct ast_cdr_config *cdr_config;
272
273         mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
274         if (!mod_cfg) {
275                 return NULL;
276         }
277
278         cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
279         if (!cdr_config) {
280                 ao2_ref(cdr_config, -1);
281                 return NULL;
282         }
283         mod_cfg->general = cdr_config;
284
285         return mod_cfg;
286 }
287
288 /*! \brief Registration object for CDR backends */
289 struct cdr_beitem {
290         char name[20];
291         char desc[80];
292         ast_cdrbe be;
293         AST_RWLIST_ENTRY(cdr_beitem) list;
294         int suspended:1;
295 };
296
297 /*! \brief List of registered backends */
298 static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
299
300 /*! \brief List of registered modifiers */
301 static AST_RWLIST_HEAD_STATIC(mo_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                 AST_STRING_FIELD(context);          /*!< The accepted context for Party A */
696                 AST_STRING_FIELD(exten);            /*!< The accepted extension for Party A */
697         );
698         struct cdr_object *next;                /*!< The next CDR object in the chain */
699         struct cdr_object *last;                /*!< The last CDR object in the chain */
700 };
701
702 /*!
703  * \brief Copy variables from one list to another
704  * \param to_list destination
705  * \param from_list source
706  * \retval The number of copied variables
707  */
708 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
709 {
710         struct ast_var_t *variables;
711         struct ast_var_t *newvariable;
712         const char *var;
713         const char *val;
714         int x = 0;
715
716         AST_LIST_TRAVERSE(from_list, variables, entries) {
717                 var = ast_var_name(variables);
718                 if (ast_strlen_zero(var)) {
719                         continue;
720                 }
721                 val = ast_var_value(variables);
722                 if (ast_strlen_zero(val)) {
723                         continue;
724                 }
725                 newvariable = ast_var_assign(var, val);
726                 if (newvariable) {
727                         AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
728                         ++x;
729                 }
730         }
731
732         return x;
733 }
734
735 /*!
736  * \brief Delete all variables from a variable list
737  * \param headp The head pointer to the variable list to delete
738  */
739 static void free_variables(struct varshead *headp)
740 {
741         struct ast_var_t *vardata;
742
743         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
744                 ast_var_delete(vardata);
745         }
746 }
747
748 /*!
749  * \brief Copy a snapshot and its details
750  * \param dst The destination
751  * \param src The source
752  */
753 static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
754 {
755         if (dst->snapshot) {
756                 ao2_t_ref(dst->snapshot, -1, "release old snapshot during copy");
757         }
758         dst->snapshot = src->snapshot;
759         ao2_t_ref(dst->snapshot, +1, "bump new snapshot during copy");
760         strcpy(dst->userfield, src->userfield);
761         dst->flags = src->flags;
762         copy_variables(&dst->variables, &src->variables);
763 }
764
765 /*!
766  * \brief Transition a \ref cdr_object to a new state
767  * \param cdr The \ref cdr_object to transition
768  * \param fn_table The \ref cdr_object_fn_table state to go to
769  */
770 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
771 {
772         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
773
774         CDR_DEBUG(mod_cfg, "%p - Transitioning CDR for %s from state %s to %s\n",
775                 cdr, cdr->party_a.snapshot->name,
776                 cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
777         cdr->fn_table = fn_table;
778         if (cdr->fn_table->init_function) {
779                 cdr->fn_table->init_function(cdr);
780         }
781 }
782 /*! \internal
783  * \brief Hash function for containers of CDRs indexing by Party A uniqueid */
784 static int cdr_object_channel_hash_fn(const void *obj, const int flags)
785 {
786         const struct cdr_object *cdr;
787         const char *key;
788
789         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
790         case OBJ_KEY:
791                 key = obj;
792                 break;
793         case OBJ_POINTER:
794                 cdr = obj;
795                 key = cdr->uniqueid;
796                 break;
797         default:
798                 ast_assert(0);
799                 return 0;
800         }
801         return ast_str_case_hash(key);
802 }
803
804 /*! \internal
805  * \brief Comparison function for containers of CDRs indexing by Party A uniqueid
806  */
807 static int cdr_object_channel_cmp_fn(void *obj, void *arg, int flags)
808 {
809     struct cdr_object *left = obj;
810     struct cdr_object *right = arg;
811     const char *right_key = arg;
812     int cmp;
813
814     switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
815     case OBJ_POINTER:
816         right_key = right->uniqueid;
817         /* Fall through */
818     case OBJ_KEY:
819         cmp = strcmp(left->uniqueid, right_key);
820         break;
821     case OBJ_PARTIAL_KEY:
822         /*
823          * We could also use a partial key struct containing a length
824          * so strlen() does not get called for every comparison instead.
825          */
826         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
827         break;
828     default:
829         /* Sort can only work on something with a full or partial key. */
830         ast_assert(0);
831         cmp = 0;
832         break;
833     }
834     return cmp ? 0 : CMP_MATCH;
835 }
836
837 /*!
838  * \brief \ref cdr_object Destructor
839  */
840 static void cdr_object_dtor(void *obj)
841 {
842         struct cdr_object *cdr = obj;
843         struct ast_var_t *it_var;
844
845         ao2_cleanup(cdr->party_a.snapshot);
846         ao2_cleanup(cdr->party_b.snapshot);
847         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
848                 ast_var_delete(it_var);
849         }
850         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
851                 ast_var_delete(it_var);
852         }
853         ast_string_field_free_memory(cdr);
854
855         ao2_cleanup(cdr->next);
856 }
857
858 /*!
859  * \brief \ref cdr_object constructor
860  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
861  *
862  * This implicitly sets the state of the newly created CDR to the Single state
863  * (\ref single_state_fn_table)
864  */
865 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
866 {
867         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
868         struct cdr_object *cdr;
869
870         ast_assert(chan != NULL);
871
872         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
873         if (!cdr) {
874                 return NULL;
875         }
876         cdr->last = cdr;
877         if (ast_string_field_init(cdr, 64)) {
878                 ao2_cleanup(cdr);
879                 return NULL;
880         }
881         ast_string_field_set(cdr, uniqueid, chan->uniqueid);
882         ast_string_field_set(cdr, name, chan->name);
883         ast_string_field_set(cdr, linkedid, chan->linkedid);
884         cdr->disposition = AST_CDR_NULL;
885         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
886
887         cdr->party_a.snapshot = chan;
888         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
889
890         CDR_DEBUG(mod_cfg, "%p - Created CDR for channel %s\n", cdr, chan->name);
891
892         cdr_object_transition_state(cdr, &single_state_fn_table);
893
894         return cdr;
895 }
896
897 /*!
898  * \brief Create a new \ref cdr_object and append it to an existing chain
899  * \param cdr The \ref cdr_object to append to
900  */
901 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
902 {
903         struct cdr_object *new_cdr;
904         struct cdr_object *it_cdr;
905         struct cdr_object *cdr_last;
906
907         cdr_last = cdr->last;
908         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
909         if (!new_cdr) {
910                 return NULL;
911         }
912         new_cdr->disposition = AST_CDR_NULL;
913
914         /* Copy over the linkedid, as it may have changed */
915         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
916         ast_string_field_set(new_cdr, appl, cdr_last->appl);
917         ast_string_field_set(new_cdr, data, cdr_last->data);
918         ast_string_field_set(new_cdr, context, cdr_last->context);
919         ast_string_field_set(new_cdr, exten, cdr_last->exten);
920
921         /*
922          * If the current CDR says to disable all future ones,
923          * keep the disable chain going
924          */
925         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
926                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
927         }
928
929         /* Copy over other Party A information */
930         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
931
932         /* Append the CDR to the end of the list */
933         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
934                 it_cdr->last = new_cdr;
935         }
936         it_cdr->last = new_cdr;
937         it_cdr->next = new_cdr;
938
939         return new_cdr;
940 }
941
942 /*!
943  * \brief Return whether or not a channel has changed its state in the dialplan, subject
944  * to endbeforehexten logic
945  *
946  * \param old_snapshot The previous state
947  * \param new_snapshot The new state
948  *
949  * \retval 0 if the state has not changed
950  * \retval 1 if the state changed
951  */
952 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
953         struct ast_channel_snapshot *new_snapshot)
954 {
955         RAII_VAR(struct module_config *, mod_cfg,
956                 ao2_global_obj_ref(module_configs), ao2_cleanup);
957
958         /* If we ignore hangup logic, don't indicate that we're executing anything new */
959         if (ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)
960                 && ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
961                 return 0;
962         }
963
964         /* When Party A is originated to an application and the application exits, the stack
965          * will attempt to clear the application and restore the dummy originate application
966          * of "AppDialX". Ignore application changes to AppDialX as a result.
967          */
968         if (strcmp(new_snapshot->appl, old_snapshot->appl) && strncasecmp(new_snapshot->appl, "appdial", 7)
969                 && (strcmp(new_snapshot->context, old_snapshot->context)
970                 || strcmp(new_snapshot->exten, old_snapshot->exten)
971                 || new_snapshot->priority != old_snapshot->priority)) {
972                 return 1;
973         }
974
975         return 0;
976 }
977
978 /*!
979  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
980  * that was created as the result of a dial operation
981  *
982  * \retval 0 the channel was not created as the result of a dial
983  * \retval 1 the channel was created as the result of a dial
984  */
985 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
986 {
987         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
988                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
989 }
990
991 /*!
992  * \brief Given two CDR snapshots, figure out who should be Party A for the
993  * resulting CDR
994  * \param left One of the snapshots
995  * \param right The other snapshot
996  * \retval The snapshot that won
997  */
998 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
999 {
1000         /* Check whether or not the party is dialed. A dialed party is never the
1001          * Party A with a party that was not dialed.
1002          */
1003         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1004                 return left;
1005         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1006                 return right;
1007         }
1008
1009         /* Try the Party A flag */
1010         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1011                 return left;
1012         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1013                 return right;
1014         }
1015
1016         /* Neither party is dialed and neither has the Party A flag - defer to
1017          * creation time */
1018         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1019                 return left;
1020         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1021                 return right;
1022         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1023                 return right;
1024         } else {
1025                 /* Okay, fine, take the left one */
1026                 return left;
1027         }
1028 }
1029
1030 /*!
1031  * Compute the duration for a \ref cdr_object
1032  */
1033 static long cdr_object_get_duration(struct cdr_object *cdr)
1034 {
1035         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1036 }
1037
1038 /*!
1039  * \brief Compute the billsec for a \ref cdr_object
1040  */
1041 static long cdr_object_get_billsec(struct cdr_object *cdr)
1042 {
1043         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1044         long int ms;
1045
1046         if (ast_tvzero(cdr->answer)) {
1047                 return 0;
1048         }
1049         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1050         if (ast_test_flag(&mod_cfg->general->settings, CDR_INITIATED_SECONDS)
1051                 && (ms % 1000 >= 500)) {
1052                 ms = (ms / 1000) + 1;
1053         } else {
1054                 ms = ms / 1000;
1055         }
1056
1057         return ms;
1058 }
1059
1060 /*!
1061  * \internal
1062  * \brief Set a variable on a CDR object
1063  *
1064  * \param headp The header pointer to the variable to set
1065  * \param name The name of the variable
1066  * \param value The value of the variable
1067  */
1068 static void set_variable(struct varshead *headp, const char *name, const char *value)
1069 {
1070         struct ast_var_t *newvariable;
1071
1072         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1073                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1074                         AST_LIST_REMOVE_CURRENT(entries);
1075                         ast_var_delete(newvariable);
1076                         break;
1077                 }
1078         }
1079         AST_LIST_TRAVERSE_SAFE_END;
1080
1081         if (value && (newvariable = ast_var_assign(name, value))) {
1082                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1083         }
1084 }
1085
1086 /*!
1087  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1088  * suitable for consumption by the registered CDR backends
1089  * \param cdr The \ref cdr_object to convert to a public record
1090  * \retval A chain of \ref ast_cdr objects on success
1091  * \retval NULL on failure
1092  */
1093 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1094 {
1095         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1096         struct cdr_object *it_cdr;
1097         struct ast_var_t *it_var, *it_copy_var;
1098         struct ast_channel_snapshot *party_a;
1099         struct ast_channel_snapshot *party_b;
1100
1101         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1102                 struct ast_cdr *cdr_copy;
1103
1104                 /* Don't create records for CDRs where the party A was a dialed channel */
1105                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1106                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1107                                 it_cdr->party_a.snapshot->name);
1108                         continue;
1109                 }
1110
1111                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1112                 if (!cdr_copy) {
1113                         ast_free(pub_cdr);
1114                         return NULL;
1115                 }
1116
1117                 party_a = it_cdr->party_a.snapshot;
1118                 party_b = it_cdr->party_b.snapshot;
1119
1120                 /* Party A */
1121                 ast_assert(party_a != NULL);
1122                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1123                 cdr_copy->amaflags = party_a->amaflags;
1124                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1125                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1126                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1127                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1128                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1129                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1130                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1131                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1132
1133                 /* Party B */
1134                 if (party_b) {
1135                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1136                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1137                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1138                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1139                         }
1140                 }
1141                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1142                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1143                 }
1144
1145                 /* Timestamps/durations */
1146                 cdr_copy->start = it_cdr->start;
1147                 cdr_copy->answer = it_cdr->answer;
1148                 cdr_copy->end = it_cdr->end;
1149                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1150                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1151
1152                 /* Flags and IDs */
1153                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1154                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1155                 cdr_copy->disposition = it_cdr->disposition;
1156                 cdr_copy->sequence = it_cdr->sequence;
1157
1158                 /* Variables */
1159                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1160                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1161                         int found = 0;
1162                         struct ast_var_t *newvariable;
1163                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1164                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1165                                         found = 1;
1166                                         break;
1167                                 }
1168                         }
1169                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1170                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1171                         }
1172                 }
1173
1174                 if (!pub_cdr) {
1175                         pub_cdr = cdr_copy;
1176                         cdr_prev = pub_cdr;
1177                 } else {
1178                         cdr_prev->next = cdr_copy;
1179                         cdr_prev = cdr_copy;
1180                 }
1181         }
1182
1183         return pub_cdr;
1184 }
1185
1186 /*!
1187  * \brief Dispatch a CDR.
1188  * \param cdr The \ref cdr_object to dispatch
1189  *
1190  * This will create a \ref ast_cdr object and publish it to the various backends
1191  */
1192 static void cdr_object_dispatch(struct cdr_object *cdr)
1193 {
1194         RAII_VAR(struct module_config *, mod_cfg,
1195                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1196         struct ast_cdr *pub_cdr;
1197
1198         CDR_DEBUG(mod_cfg, "%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1199                         cdr->party_a.snapshot->name,
1200                         cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1201         pub_cdr = cdr_object_create_public_records(cdr);
1202         cdr_detach(pub_cdr);
1203 }
1204
1205 /*!
1206  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1207  * \param cdr The \ref cdr_object
1208  * \param hangupcause The Asterisk hangup cause code
1209  */
1210 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1211 {
1212         RAII_VAR(struct module_config *, mod_cfg,
1213                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1214
1215         /* Change the disposition based on the hang up cause */
1216         switch (hangupcause) {
1217         case AST_CAUSE_BUSY:
1218                 cdr->disposition = AST_CDR_BUSY;
1219                 break;
1220         case AST_CAUSE_CONGESTION:
1221                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1222                         cdr->disposition = AST_CDR_FAILED;
1223                 } else {
1224                         cdr->disposition = AST_CDR_CONGESTION;
1225                 }
1226                 break;
1227         case AST_CAUSE_NO_ROUTE_DESTINATION:
1228         case AST_CAUSE_UNREGISTERED:
1229                 cdr->disposition = AST_CDR_FAILED;
1230                 break;
1231         case AST_CAUSE_NORMAL_CLEARING:
1232         case AST_CAUSE_NO_ANSWER:
1233                 cdr->disposition = AST_CDR_NOANSWER;
1234                 break;
1235         default:
1236                 break;
1237         }
1238 }
1239
1240 /*!
1241  * \brief Finalize a CDR.
1242  *
1243  * This function is safe to call multiple times. Note that you can call this
1244  * explicitly before going to the finalized state if there's a chance the CDR
1245  * will be re-activated, in which case the \ref cdr_object's end time should be
1246  * cleared. This function is implicitly called when a CDR transitions to the
1247  * finalized state and right before it is dispatched
1248  *
1249  * \param cdr_object The CDR to finalize
1250  */
1251 static void cdr_object_finalize(struct cdr_object *cdr)
1252 {
1253         if (!ast_tvzero(cdr->end)) {
1254                 return;
1255         }
1256         cdr->end = ast_tvnow();
1257
1258         if (cdr->disposition == AST_CDR_NULL) {
1259                 if (!ast_tvzero(cdr->answer)) {
1260                         cdr->disposition = AST_CDR_ANSWERED;
1261                 } else if (cdr->party_a.snapshot->hangupcause) {
1262                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1263                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1264                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1265                 } else {
1266                         cdr->disposition = AST_CDR_FAILED;
1267                 }
1268         }
1269
1270         /* tv_usec is suseconds_t, which could be int or long */
1271         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1272                         cdr->party_a.snapshot->name,
1273                         (long)cdr->start.tv_sec,
1274                         (long)cdr->start.tv_usec,
1275                         (long)cdr->answer.tv_sec,
1276                         (long)cdr->answer.tv_usec,
1277                         (long)cdr->end.tv_sec,
1278                         (long)cdr->end.tv_usec,
1279                         ast_cdr_disp2str(cdr->disposition));
1280 }
1281
1282 /*!
1283  * \brief Check to see if a CDR needs to move to the finalized state because
1284  * its Party A hungup.
1285  */
1286 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1287 {
1288         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1289
1290         if (ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)
1291                 && ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1292                 cdr_object_finalize(cdr);
1293         }
1294
1295         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1296                 && cdr->fn_table != &finalized_state_fn_table) {
1297                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1298         }
1299 }
1300
1301 /*!
1302  * \brief Check to see if a CDR needs to be answered based on its Party A.
1303  * Note that this is safe to call as much as you want - we won't answer twice
1304  */
1305 static void cdr_object_check_party_a_answer(struct cdr_object *cdr) {
1306         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1307
1308         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1309                 cdr->answer = ast_tvnow();
1310                 /* tv_usec is suseconds_t, which could be int or long */
1311                 CDR_DEBUG(mod_cfg, "%p - Set answered time to %ld.%06ld\n", cdr,
1312                         (long)cdr->answer.tv_sec,
1313                         (long)cdr->answer.tv_usec);
1314         }
1315 }
1316
1317 /* \brief Set Caller ID information on a CDR */
1318 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1319 {
1320         if (!old_snapshot->snapshot) {
1321                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1322                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1323                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1324                 return;
1325         }
1326         if (!strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1327                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1328         }
1329         if (!strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1330                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1331         }
1332         if (!strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1333                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1334         }
1335 }
1336
1337 /*!
1338  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1339  * a new \ref ast_channel_snapshot
1340  * \param old_snapshot The old \ref cdr_object_snapshot
1341  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1342  */
1343 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1344                 struct ast_channel_snapshot *new_snapshot)
1345 {
1346         cdr_object_update_cid(old_snapshot, new_snapshot);
1347         if (old_snapshot->snapshot) {
1348                 ao2_t_ref(old_snapshot->snapshot, -1, "Drop ref for swap");
1349         }
1350         ao2_t_ref(new_snapshot, +1, "Bump ref for swap");
1351         old_snapshot->snapshot = new_snapshot;
1352 }
1353
1354 /* BASE METHOD IMPLEMENTATIONS */
1355
1356 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1357 {
1358         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1359
1360         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1361
1362         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1363         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1364                 && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)) {
1365                 cdr_object_finalize(cdr);
1366                 return 0;
1367         }
1368
1369         /*
1370          * Only record the context and extension if we aren't in a subroutine, or if
1371          * we are executing hangup logic.
1372          */
1373         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1374                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1375                 ast_string_field_set(cdr, context, snapshot->context);
1376                 ast_string_field_set(cdr, exten, snapshot->exten);
1377         }
1378
1379         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1380
1381         /* When Party A is originated to an application and the application exits, the stack
1382          * will attempt to clear the application and restore the dummy originate application
1383          * of "AppDialX". Prevent that, and any other application changes we might not want
1384          * here.
1385          */
1386         if (!ast_strlen_zero(snapshot->appl)
1387                         && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))
1388                         && !ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)) {
1389                 ast_string_field_set(cdr, appl, snapshot->appl);
1390                 ast_string_field_set(cdr, data, snapshot->data);
1391
1392                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1393                  * execute before the dial begins, will alter the application/data to
1394                  * something people typically don't want to see, if we see a channel enter
1395                  * into Dial here, we set the appl/data accordingly and lock it.
1396                  */
1397                 if (!strcmp(snapshot->appl, "Dial")) {
1398                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1399                 }
1400         }
1401
1402         ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1403         cdr_object_check_party_a_answer(cdr);
1404         cdr_object_check_party_a_hangup(cdr);
1405
1406         return 0;
1407 }
1408
1409 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1410 {
1411         /* In general, most things shouldn't get a bridge leave */
1412         ast_assert(0);
1413         return 1;
1414 }
1415
1416 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1417 {
1418         /* In general, most things shouldn't get a dial end. */
1419         ast_assert(0);
1420         return 0;
1421 }
1422
1423 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1424 {
1425         /* Base process bridge enter simply indicates that we can't handle it */
1426         return BRIDGE_ENTER_NEED_CDR;
1427 }
1428
1429 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1430 {
1431         char park_info[128];
1432
1433         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1434
1435         /* Update Party A information regardless */
1436         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1437
1438         /* Fake out where we're parked */
1439         ast_string_field_set(cdr, appl, "Park");
1440         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1441         ast_string_field_set(cdr, data, park_info);
1442
1443         /* Prevent any further changes to the App/Data fields for this record */
1444         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1445
1446         return 0;
1447 }
1448
1449 /* SINGLE STATE */
1450
1451 static void single_state_init_function(struct cdr_object *cdr) {
1452         cdr->start = ast_tvnow();
1453         cdr_object_check_party_a_answer(cdr);
1454 }
1455
1456 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1457 {
1458         /* This should never happen! */
1459         ast_assert(cdr->party_b.snapshot == NULL);
1460         ast_assert(0);
1461         return;
1462 }
1463
1464 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1465 {
1466         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1467
1468         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1469                 base_process_party_a(cdr, caller);
1470                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1471                                 cdr->party_a.snapshot->name);
1472                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1473                 CDR_DEBUG(mod_cfg, "%p - Updated Party B %s snapshot\n", cdr,
1474                                 cdr->party_b.snapshot->name);
1475
1476                 /* If we have two parties, lock the application that caused the
1477                  * two parties to be associated. This prevents mid-call event
1478                  * macros/gosubs from perturbing the CDR application/data
1479                  */
1480                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1481         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1482                 /* We're the entity being dialed, i.e., outbound origination */
1483                 base_process_party_a(cdr, peer);
1484                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1485                                 cdr->party_a.snapshot->name);
1486         }
1487
1488         cdr_object_transition_state(cdr, &dial_state_fn_table);
1489         return 0;
1490 }
1491
1492 /*!
1493  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1494  * already in the bridge while in the Single state. The goal of this is to find
1495  * a Party B for our CDR.
1496  *
1497  * \param cdr Our \ref cdr_object in the Single state
1498  * \param cand_cdr The \ref cdr_object already in the Bridge state
1499  *
1500  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1501  * Party B
1502  * \retval 1 No party in the cand_cdr could be used as our Party B
1503  */
1504 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1505                 struct cdr_object *cand_cdr)
1506 {
1507         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1508         struct cdr_object_snapshot *party_a;
1509
1510         /* Don't match on ourselves */
1511         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1512                 return 1;
1513         }
1514
1515         /* Try the candidate CDR's Party A first */
1516         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1517         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1518                 CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
1519                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1520                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1521                 if (!cand_cdr->party_b.snapshot) {
1522                         /* We just stole them - finalize their CDR. Note that this won't
1523                          * transition their state, it just sets the end time and the
1524                          * disposition - if we need to re-activate them later, we can.
1525                          */
1526                         cdr_object_finalize(cand_cdr);
1527                 }
1528                 return 0;
1529         }
1530
1531         /* Try their Party B, unless it's us */
1532         if (!cand_cdr->party_b.snapshot
1533                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1534                 return 1;
1535         }
1536         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1537         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1538                 CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
1539                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1540                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1541                 return 0;
1542         }
1543
1544         return 1;
1545 }
1546
1547 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)
1548 {
1549         struct ao2_iterator it_cdrs;
1550         char *channel_id;
1551         int success = 0;
1552
1553         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1554
1555         if (ao2_container_count(bridge->channels) == 1) {
1556                 /* No one in the bridge yet but us! */
1557                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1558                 return BRIDGE_ENTER_ONLY_PARTY;
1559         }
1560
1561         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1562                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1563                 ao2_ref(channel_id, -1)) {
1564                 RAII_VAR(struct cdr_object *, cand_cdr_master,
1565                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
1566                         ao2_cleanup);
1567                 struct cdr_object *cand_cdr;
1568
1569                 if (!cand_cdr_master) {
1570                         continue;
1571                 }
1572
1573                 ao2_lock(cand_cdr_master);
1574                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1575                         /* Skip any records that are not in a bridge or in this bridge.
1576                          * I'm not sure how that would happen, but it pays to be careful. */
1577                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1578                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1579                                 continue;
1580                         }
1581
1582                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1583                                 continue;
1584                         }
1585                         /* We successfully got a party B - break out */
1586                         success = 1;
1587                         break;
1588                 }
1589                 ao2_unlock(cand_cdr_master);
1590         }
1591         ao2_iterator_destroy(&it_cdrs);
1592
1593         /* We always transition state, even if we didn't get a peer */
1594         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1595
1596         /* Success implies that we have a Party B */
1597         if (success) {
1598                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1599         }
1600
1601         return BRIDGE_ENTER_NO_PARTY_B;
1602 }
1603
1604 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1605 {
1606         cdr_object_transition_state(cdr, &parked_state_fn_table);
1607         return 0;
1608 }
1609
1610
1611 /* DIAL STATE */
1612
1613 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1614 {
1615         ast_assert(snapshot != NULL);
1616
1617         if (!cdr->party_b.snapshot
1618                 || strcasecmp(cdr->party_b.snapshot->name, snapshot->name)) {
1619                 return;
1620         }
1621         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1622
1623         /* If party B hangs up, finalize this CDR */
1624         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1625                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1626         }
1627 }
1628
1629 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1630 {
1631         /* Don't process a begin dial here. A party A already in the dial state will
1632          * who receives a dial begin for something else will be handled by the
1633          * message router callback and will add a new CDR for the party A */
1634         return 1;
1635 }
1636
1637 /*!
1638  * \internal
1639  * \brief Convert a dial status to a CDR disposition
1640  */
1641 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1642 {
1643         RAII_VAR(struct module_config *, mod_cfg,
1644                 ao2_global_obj_ref(module_configs), ao2_cleanup);
1645
1646         if (!strcmp(dial_status, "ANSWER")) {
1647                 return AST_CDR_ANSWERED;
1648         } else if (!strcmp(dial_status, "BUSY")) {
1649                 return AST_CDR_BUSY;
1650         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1651                 return AST_CDR_NOANSWER;
1652         } else if (!strcmp(dial_status, "CONGESTION")) {
1653                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1654                         return AST_CDR_FAILED;
1655                 } else {
1656                         return AST_CDR_CONGESTION;
1657                 }
1658         } else if (!strcmp(dial_status, "FAILED")) {
1659                 return AST_CDR_FAILED;
1660         }
1661         return AST_CDR_FAILED;
1662 }
1663
1664 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)
1665 {
1666         struct ast_channel_snapshot *party_a;
1667
1668         if (caller) {
1669                 party_a = caller;
1670         } else {
1671                 party_a = peer;
1672         }
1673         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1674         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1675
1676         if (cdr->party_b.snapshot) {
1677                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1678                         /* Not the status for this CDR - defer back to the message router */
1679                         return 1;
1680                 }
1681                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1682         }
1683
1684         /* Set the disposition based on the dial string. */
1685         cdr->disposition = dial_status_to_disposition(dial_status);
1686         if (cdr->disposition == AST_CDR_ANSWERED) {
1687                 /* Switch to dial pending to wait and see what the caller does */
1688                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1689         } else {
1690                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1691         }
1692
1693         return 0;
1694 }
1695
1696 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)
1697 {
1698         struct ao2_iterator it_cdrs;
1699         char *channel_id;
1700         int success = 0;
1701
1702         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1703
1704         /* Get parties in the bridge */
1705         if (ao2_container_count(bridge->channels) == 1) {
1706                 /* No one in the bridge yet but us! */
1707                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1708                 return BRIDGE_ENTER_ONLY_PARTY;
1709         }
1710
1711         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1712                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1713                 ao2_ref(channel_id, -1)) {
1714                 RAII_VAR(struct cdr_object *, cand_cdr_master,
1715                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
1716                         ao2_cleanup);
1717                 struct cdr_object *cand_cdr;
1718
1719                 if (!cand_cdr_master) {
1720                         continue;
1721                 }
1722
1723                 ao2_lock(cand_cdr_master);
1724                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1725                         /* Skip any records that are not in a bridge or in this bridge.
1726                          * I'm not sure how that would happen, but it pays to be careful. */
1727                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1728                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1729                                 continue;
1730                         }
1731
1732                         /* If we don't have a Party B (originated channel), skip it */
1733                         if (!cdr->party_b.snapshot) {
1734                                 continue;
1735                         }
1736
1737                         /* Skip any records that aren't our Party B */
1738                         if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1739                                 continue;
1740                         }
1741                         cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1742                         /* If they have a Party B, they joined up with someone else as their
1743                          * Party A. Don't finalize them as they're active. Otherwise, we
1744                          * have stolen them so they need to be finalized.
1745                          */
1746                         if (!cand_cdr->party_b.snapshot) {
1747                                 cdr_object_finalize(cand_cdr);
1748                         }
1749                         success = 1;
1750                         break;
1751                 }
1752                 ao2_unlock(cand_cdr_master);
1753         }
1754         ao2_iterator_destroy(&it_cdrs);
1755
1756         /* We always transition state, even if we didn't get a peer */
1757         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1758
1759         /* Success implies that we have a Party B */
1760         if (success) {
1761                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1762         }
1763         return BRIDGE_ENTER_NO_PARTY_B;
1764 }
1765
1766 /* DIALED PENDING STATE */
1767
1768 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1769 {
1770         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1771          * that means we need a new CDR; otherwise, switch us over to single.
1772          */
1773         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1774                 if (cdr->party_b.snapshot) {
1775                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1776                         cdr->fn_table->process_party_a(cdr, snapshot);
1777                         return 1;
1778                 } else {
1779                         cdr_object_transition_state(cdr, &single_state_fn_table);
1780                         cdr->fn_table->process_party_a(cdr, snapshot);
1781                         return 0;
1782                 }
1783         }
1784         base_process_party_a(cdr, snapshot);
1785         return 0;
1786 }
1787
1788 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)
1789 {
1790         cdr_object_transition_state(cdr, &dial_state_fn_table);
1791         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1792 }
1793
1794 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1795 {
1796         if (cdr->party_b.snapshot) {
1797                 /* We can't handle this as we have a Party B - ask for a new one */
1798                 return 1;
1799         }
1800         cdr_object_transition_state(cdr, &parked_state_fn_table);
1801         return 0;
1802 }
1803
1804 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1805 {
1806         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1807
1808         /* Ask for a new CDR */
1809         return 1;
1810 }
1811
1812 /* BRIDGE STATE */
1813
1814 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1815 {
1816         if (!cdr->party_b.snapshot
1817                 || strcasecmp(cdr->party_b.snapshot->name, snapshot->name)) {
1818                 return;
1819         }
1820         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1821
1822         /* If party B hangs up, finalize this CDR */
1823         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1824                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1825         }
1826 }
1827
1828 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1829 {
1830         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1831                 return 1;
1832         }
1833         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
1834                 && cdr->party_b.snapshot
1835                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
1836                 return 1;
1837         }
1838         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1839
1840         return 0;
1841 }
1842
1843 /* PARKED STATE */
1844
1845 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1846 {
1847         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
1848                 return 1;
1849         }
1850         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1851
1852         return 0;
1853 }
1854
1855 /* FINALIZED STATE */
1856
1857 static void finalized_state_init_function(struct cdr_object *cdr)
1858 {
1859         cdr_object_finalize(cdr);
1860 }
1861
1862 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1863 {
1864         RAII_VAR(struct module_config *, mod_cfg,
1865                 ao2_global_obj_ref(module_configs), ao2_cleanup);
1866
1867         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1868                         && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)) {
1869                 return 0;
1870         }
1871
1872         /* Indicate that, if possible, we should get a new CDR */
1873         return 1;
1874 }
1875
1876 /*!
1877  * \internal
1878  * \brief Filter channel snapshots by technology
1879  */
1880 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1881 {
1882         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
1883 }
1884
1885 /*!
1886  * \internal
1887  * \brief Filter a channel cache update
1888  */
1889 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
1890                 struct ast_channel_snapshot *new_snapshot)
1891 {
1892         int ret = 0;
1893
1894         /* Drop cache updates from certain channel technologies */
1895         if (old_snapshot) {
1896                 ret |= filter_channel_snapshot(old_snapshot);
1897         }
1898         if (new_snapshot) {
1899                 ret |= filter_channel_snapshot(new_snapshot);
1900         }
1901
1902         return ret;
1903 }
1904
1905 /* TOPIC ROUTER CALLBACKS */
1906
1907 /*!
1908  * \brief Handler for Stasis-Core dial messages
1909  * \param data Passed on
1910  * \param sub The stasis subscription for this message callback
1911  * \param topic The topic this message was published for
1912  * \param message The message
1913  */
1914 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
1915 {
1916         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1917         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
1918         struct ast_multi_channel_blob *payload = stasis_message_data(message);
1919         struct ast_channel_snapshot *caller;
1920         struct ast_channel_snapshot *peer;
1921         struct cdr_object *it_cdr;
1922         struct ast_json *dial_status_blob;
1923         const char *dial_status = NULL;
1924         int res = 1;
1925
1926         caller = ast_multi_channel_blob_get_channel(payload, "caller");
1927         peer = ast_multi_channel_blob_get_channel(payload, "peer");
1928         if (!peer && !caller) {
1929                 return;
1930         }
1931         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
1932         if (dial_status_blob) {
1933                 dial_status = ast_json_string_get(dial_status_blob);
1934         }
1935
1936         CDR_DEBUG(mod_cfg, "Dial %s message for %s, %s: %u.%08u\n",
1937                         ast_strlen_zero(dial_status) ? "Begin" : "End",
1938                         caller ? caller->name : "(none)",
1939                         peer ? peer->name : "(none)",
1940                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
1941                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
1942
1943         if (filter_channel_snapshot(peer) || (caller && filter_channel_snapshot(caller))) {
1944                 return;
1945         }
1946
1947         /* Figure out who is running this show */
1948         if (caller) {
1949                 cdr = ao2_find(active_cdrs_by_channel, caller->uniqueid, OBJ_KEY);
1950         } else {
1951                 cdr = ao2_find(active_cdrs_by_channel, peer->uniqueid, OBJ_KEY);
1952         }
1953
1954         if (!cdr) {
1955                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
1956                 ast_assert(0);
1957                 return;
1958         }
1959
1960         ao2_lock(cdr);
1961         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1962                 if (ast_strlen_zero(dial_status)) {
1963                         if (!it_cdr->fn_table->process_dial_begin) {
1964                                 continue;
1965                         }
1966                         CDR_DEBUG(mod_cfg, "%p - Processing Dial Begin message for channel %s, peer %s\n",
1967                                         it_cdr,
1968                                         caller ? caller->name : "(none)",
1969                                         peer ? peer->name : "(none)");
1970                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
1971                                         caller,
1972                                         peer);
1973                 } else {
1974                         if (!it_cdr->fn_table->process_dial_end) {
1975                                 continue;
1976                         }
1977                         CDR_DEBUG(mod_cfg, "%p - Processing Dial End message for channel %s, peer %s\n",
1978                                         it_cdr,
1979                                         caller ? caller->name : "(none)",
1980                                         peer ? peer->name : "(none)");
1981                         it_cdr->fn_table->process_dial_end(it_cdr,
1982                                         caller,
1983                                         peer,
1984                                         dial_status);
1985                 }
1986         }
1987
1988         /* If no CDR handled a dial begin message, make a new one */
1989         if (res && ast_strlen_zero(dial_status)) {
1990                 struct cdr_object *new_cdr;
1991
1992                 new_cdr = cdr_object_create_and_append(cdr);
1993                 if (!new_cdr) {
1994                         ao2_unlock(cdr);
1995                         return;
1996                 }
1997                 new_cdr->fn_table->process_dial_begin(new_cdr,
1998                                 caller,
1999                                 peer);
2000         }
2001         ao2_unlock(cdr);
2002 }
2003
2004 static int cdr_object_finalize_party_b(void *obj, void *arg, int flags)
2005 {
2006         struct cdr_object *cdr = obj;
2007         struct ast_channel_snapshot *party_b = arg;
2008         struct cdr_object *it_cdr;
2009         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2010                 if (it_cdr->party_b.snapshot
2011                         && !strcasecmp(it_cdr->party_b.snapshot->name, party_b->name)) {
2012                         /* Don't transition to the finalized state - let the Party A do
2013                          * that when its ready
2014                          */
2015                         cdr_object_finalize(it_cdr);
2016                 }
2017         }
2018         return 0;
2019 }
2020
2021 static int cdr_object_update_party_b(void *obj, void *arg, int flags)
2022 {
2023         struct cdr_object *cdr = obj;
2024         struct ast_channel_snapshot *party_b = arg;
2025         struct cdr_object *it_cdr;
2026         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2027                 if (!it_cdr->fn_table->process_party_b) {
2028                         continue;
2029                 }
2030                 if (it_cdr->party_b.snapshot
2031                         && !strcasecmp(it_cdr->party_b.snapshot->name, party_b->name)) {
2032                         it_cdr->fn_table->process_party_b(it_cdr, party_b);
2033                 }
2034         }
2035         return 0;
2036 }
2037
2038 /*! \brief Determine if we need to add a new CDR based on snapshots */
2039 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2040                 struct ast_channel_snapshot *new_snapshot)
2041 {
2042         RAII_VAR(struct module_config *, mod_cfg,
2043                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2044
2045         /* If we're dead, we don't need a new CDR */
2046         if (!new_snapshot
2047                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2048                         && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN))) {
2049                 return 0;
2050         }
2051
2052         /* Auto-fall through will increment the priority but have no application */
2053         if (ast_strlen_zero(new_snapshot->appl)) {
2054                 return 0;
2055         }
2056
2057         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2058                 return 0;
2059         }
2060
2061         return 1;
2062 }
2063
2064 /*!
2065  * \brief Handler for Stasis-Core channel cache update messages
2066  * \param data Passed on
2067  * \param sub The stasis subscription for this message callback
2068  * \param topic The topic this message was published for
2069  * \param message The message
2070  */
2071 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2072 {
2073         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
2074         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2075         struct stasis_cache_update *update = stasis_message_data(message);
2076         struct ast_channel_snapshot *old_snapshot;
2077         struct ast_channel_snapshot *new_snapshot;
2078         const char *uniqueid;
2079         const char *name;
2080         struct cdr_object *it_cdr;
2081
2082         ast_assert(update != NULL);
2083         ast_assert(ast_channel_snapshot_type() == update->type);
2084
2085         old_snapshot = stasis_message_data(update->old_snapshot);
2086         new_snapshot = stasis_message_data(update->new_snapshot);
2087         uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2088         name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2089
2090         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2091                 return;
2092         }
2093
2094         if (new_snapshot && !old_snapshot) {
2095                 cdr = cdr_object_alloc(new_snapshot);
2096                 if (!cdr) {
2097                         return;
2098                 }
2099                 ao2_link(active_cdrs_by_channel, cdr);
2100         }
2101
2102         /* Handle Party A */
2103         if (!cdr) {
2104                 cdr = ao2_find(active_cdrs_by_channel, uniqueid, OBJ_KEY);
2105         }
2106         if (!cdr) {
2107                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2108                 ast_assert(0);
2109         } else {
2110                 ao2_lock(cdr);
2111                 if (new_snapshot) {
2112                         int all_reject = 1;
2113                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2114                                 if (!it_cdr->fn_table->process_party_a) {
2115                                         continue;
2116                                 }
2117                                 all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2118                         }
2119                         if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2120                                 /* We're not hung up and we have a new snapshot - we need a new CDR */
2121                                 struct cdr_object *new_cdr;
2122                                 new_cdr = cdr_object_create_and_append(cdr);
2123                                 if (new_cdr) {
2124                                         new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2125                                 }
2126                         }
2127                 } else {
2128                         CDR_DEBUG(mod_cfg, "%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2129                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2130                                 cdr_object_finalize(it_cdr);
2131                         }
2132                         cdr_object_dispatch(cdr);
2133                         ao2_unlink(active_cdrs_by_channel, cdr);
2134                 }
2135                 ao2_unlock(cdr);
2136         }
2137
2138         /* Handle Party B */
2139         if (new_snapshot) {
2140                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_update_party_b,
2141                         new_snapshot);
2142         } else {
2143                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_finalize_party_b,
2144                         old_snapshot);
2145         }
2146
2147 }
2148
2149 struct bridge_leave_data {
2150         struct ast_bridge_snapshot *bridge;
2151         struct ast_channel_snapshot *channel;
2152 };
2153
2154 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2155 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, int flags)
2156 {
2157         struct cdr_object *cdr = obj;
2158         struct bridge_leave_data *leave_data = arg;
2159         struct cdr_object *it_cdr;
2160
2161         if (strcmp(cdr->bridge, leave_data->bridge->uniqueid)) {
2162                 return 0;
2163         }
2164         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2165                 if (it_cdr->fn_table != &bridge_state_fn_table) {
2166                         continue;
2167                 }
2168                 if (!it_cdr->party_b.snapshot) {
2169                         continue;
2170                 }
2171                 if (strcasecmp(it_cdr->party_b.snapshot->name, leave_data->channel->name)) {
2172                         continue;
2173                 }
2174                 /* It is our Party B, in our bridge. Set the end time and let the handler
2175                  * transition our CDR appropriately when we leave the bridge.
2176                  */
2177                 cdr_object_finalize(it_cdr);
2178         }
2179         return 0;
2180 }
2181
2182 /*! \brief Filter bridge messages based on bridge technology */
2183 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2184 {
2185         /* Ignore holding bridge technology messages. We treat this simply as an application
2186          * that a channel enters into.
2187          */
2188         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2189                 return 1;
2190         }
2191         return 0;
2192 }
2193
2194 /*!
2195  * \brief Handler for when a channel leaves a bridge
2196  * \param data Passed on
2197  * \param sub The stasis subscription for this message callback
2198  * \param topic The topic this message was published for
2199  * \param message The message - hopefully a bridge one!
2200  */
2201 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2202                 struct stasis_message *message)
2203 {
2204         struct ast_bridge_blob *update = stasis_message_data(message);
2205         struct ast_bridge_snapshot *bridge = update->bridge;
2206         struct ast_channel_snapshot *channel = update->channel;
2207         RAII_VAR(struct module_config *, mod_cfg,
2208                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2209         RAII_VAR(struct cdr_object *, cdr,
2210                         ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY),
2211                         ao2_cleanup);
2212         struct cdr_object *it_cdr;
2213         struct bridge_leave_data leave_data = {
2214                 .bridge = bridge,
2215                 .channel = channel,
2216         };
2217         int left_bridge = 0;
2218
2219         if (filter_bridge_messages(bridge)) {
2220                 return;
2221         }
2222
2223         if (filter_channel_snapshot(channel)) {
2224                 return;
2225         }
2226
2227         CDR_DEBUG(mod_cfg, "Bridge Leave message for %s: %u.%08u\n",
2228                         channel->name,
2229                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2230                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2231
2232         if (!cdr) {
2233                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2234                 ast_assert(0);
2235                 return;
2236         }
2237
2238         /* Party A */
2239         ao2_lock(cdr);
2240         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2241                 if (!it_cdr->fn_table->process_bridge_leave) {
2242                         continue;
2243                 }
2244                 CDR_DEBUG(mod_cfg, "%p - Processing Bridge Leave for %s\n",
2245                                 it_cdr, channel->name);
2246                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2247                         ast_string_field_set(it_cdr, bridge, "");
2248                         left_bridge = 1;
2249                 }
2250         }
2251         ao2_unlock(cdr);
2252         if (!left_bridge) {
2253                 return;
2254         }
2255
2256         if (strcmp(bridge->subclass, "parking")) {
2257                 /* Party B */
2258                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA,
2259                                 cdr_object_party_b_left_bridge_cb,
2260                                 &leave_data);
2261         }
2262 }
2263
2264 /*!
2265  * \internal
2266  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2267  *
2268  * \note The new CDR will be automatically transitioned to the bridge state
2269  */
2270 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2271                 struct cdr_object_snapshot *party_b)
2272 {
2273         RAII_VAR(struct module_config *,  mod_cfg,
2274                 ao2_global_obj_ref(module_configs), ao2_cleanup);
2275         struct cdr_object *new_cdr;
2276
2277         new_cdr = cdr_object_create_and_append(cdr);
2278         if (!new_cdr) {
2279                 return;
2280         }
2281         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2282         cdr_object_check_party_a_answer(new_cdr);
2283         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2284         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2285         CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
2286                 new_cdr, new_cdr->party_a.snapshot->name,
2287                 party_b->snapshot->name);
2288 }
2289
2290 /*!
2291  * \brief Process a single \ref bridge_candidate
2292  *
2293  * When a CDR enters a bridge, it needs to make pairings with everyone else
2294  * that it is not currently paired with. This function determines, for the
2295  * CDR for the channel that entered the bridge and the CDR for every other
2296  * channel currently in the bridge, who is Party A and makes new CDRs.
2297  *
2298  * \param cdr The \ref cdr_obj being processed
2299  * \param cand_cdr The \ref cdr_object that is a candidate
2300  *
2301  */
2302 static int bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2303 {
2304         RAII_VAR(struct module_config *, mod_cfg,
2305                 ao2_global_obj_ref(module_configs), ao2_cleanup);
2306         struct cdr_object_snapshot *party_a;
2307         struct cdr_object *cand_cdr;
2308
2309         SCOPED_AO2LOCK(lock, base_cand_cdr);
2310
2311         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2312                 /* Skip any records that are not in this bridge */
2313                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2314                         continue;
2315                 }
2316
2317                 /* If the candidate is us or someone we've taken on, pass on by */
2318                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2319                         || (cdr->party_b.snapshot
2320                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2321                         return 0;
2322                 }
2323
2324                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2325                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2326                  * Party B */
2327                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2328                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2329                         return 0;
2330                 }
2331
2332                 /* We're Party B. Check if we can add ourselves immediately or if we need
2333                  * a new CDR for them (they already have a Party B) */
2334                 if (cand_cdr->party_b.snapshot
2335                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2336                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2337                 } else {
2338                         CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
2339                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2340                                 cdr->party_a.snapshot->name);
2341                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2342                         /* It's possible that this joined at one point and was never chosen
2343                          * as party A. Clear their end time, as it would be set in such a
2344                          * case.
2345                          */
2346                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2347                 }
2348                 return 0;
2349         }
2350         return 0;
2351 }
2352
2353 /*!
2354  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2355  * entered a bridge
2356  * \param cdr The \ref cdr_object that just entered the bridge
2357  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2358  */
2359 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2360 {
2361         struct ao2_iterator it_channels;
2362         char *channel_id;
2363
2364         it_channels = ao2_iterator_init(bridge->channels, 0);
2365         while ((channel_id = ao2_iterator_next(&it_channels))) {
2366                 RAII_VAR(struct cdr_object *, cand_cdr,
2367                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
2368                         ao2_cleanup);
2369
2370                 if (!cand_cdr) {
2371                         ao2_ref(channel_id, -1);
2372                         continue;
2373                 }
2374
2375                 bridge_candidate_process(cdr, cand_cdr);
2376
2377                 ao2_ref(channel_id, -1);
2378         }
2379         ao2_iterator_destroy(&it_channels);
2380 }
2381
2382 /*! \brief Handle entering into a parking bridge
2383  * \param cdr The CDR to operate on
2384  * \param bridge The bridge the channel just entered
2385  * \param channel The channel snapshot
2386  */
2387 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2388                 struct ast_bridge_snapshot *bridge,
2389                 struct ast_channel_snapshot *channel)
2390 {
2391         RAII_VAR(struct module_config *, mod_cfg,
2392                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2393         int res = 1;
2394         struct cdr_object *it_cdr;
2395         struct cdr_object *new_cdr;
2396
2397         ao2_lock(cdr);
2398
2399         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2400                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2401                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2402                 }
2403                 if (it_cdr->fn_table->process_party_a) {
2404                         CDR_DEBUG(mod_cfg, "%p - Updating Party A %s snapshot\n", it_cdr,
2405                                         channel->name);
2406                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2407                 }
2408         }
2409
2410         if (res) {
2411                 /* No one handled it - we need a new one! */
2412                 new_cdr = cdr_object_create_and_append(cdr);
2413                 if (new_cdr) {
2414                         /* Let the single state transition us to Parked */
2415                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2416                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2417                 }
2418         }
2419         ao2_unlock(cdr);
2420 }
2421
2422 /*! \brief Handle a bridge enter message for a 'normal' bridge
2423  * \param cdr The CDR to operate on
2424  * \param bridge The bridge the channel just entered
2425  * \param channel The channel snapshot
2426  */
2427 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2428                 struct ast_bridge_snapshot *bridge,
2429                 struct ast_channel_snapshot *channel)
2430 {
2431         RAII_VAR(struct module_config *, mod_cfg,
2432                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2433         enum process_bridge_enter_results result;
2434         struct cdr_object *it_cdr;
2435         struct cdr_object *new_cdr;
2436         struct cdr_object *handled_cdr = NULL;
2437
2438         ao2_lock(cdr);
2439
2440         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2441                 if (it_cdr->fn_table->process_party_a) {
2442                         CDR_DEBUG(mod_cfg, "%p - Updating Party A %s snapshot\n", it_cdr,
2443                                         channel->name);
2444                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2445                 }
2446
2447                 /* Notify all states that they have entered a bridge */
2448                 if (it_cdr->fn_table->process_bridge_enter) {
2449                         CDR_DEBUG(mod_cfg, "%p - Processing bridge enter for %s\n", it_cdr,
2450                                         channel->name);
2451                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2452                         switch (result) {
2453                         case BRIDGE_ENTER_ONLY_PARTY:
2454                                 /* Fall through */
2455                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2456                                 if (!handled_cdr) {
2457                                         handled_cdr = it_cdr;
2458                                 }
2459                                 break;
2460                         case BRIDGE_ENTER_NEED_CDR:
2461                                 /* Pass */
2462                                 break;
2463                         case BRIDGE_ENTER_NO_PARTY_B:
2464                                 /* We didn't win on any - end this CDR. If someone else comes in later
2465                                  * that is Party B to this CDR, it can re-activate this CDR.
2466                                  */
2467                                 if (!handled_cdr) {
2468                                         handled_cdr = it_cdr;
2469                                 }
2470                                 cdr_object_finalize(cdr);
2471                                 break;
2472                         }
2473                 }
2474         }
2475
2476         /* Create the new matchings, but only for either:
2477          *  * The first CDR in the chain that handled it. This avoids issues with
2478          *    forked CDRs.
2479          *  * If no one handled it, the last CDR in the chain. This would occur if
2480          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2481          *    to make pairings with everyone in the bridge.
2482          */
2483         if (handled_cdr) {
2484                 handle_bridge_pairings(handled_cdr, bridge);
2485         } else {
2486                 /* Nothing handled it - we need a new one! */
2487                 new_cdr = cdr_object_create_and_append(cdr);
2488                 if (new_cdr) {
2489                         /* This is guaranteed to succeed: the new CDR is created in the single state
2490                          * and will be able to handle the bridge enter message
2491                          */
2492                         handle_standard_bridge_enter_message(cdr, bridge, channel);
2493                 }
2494         }
2495         ao2_unlock(cdr);
2496 }
2497
2498 /*!
2499  * \internal
2500  * \brief Handler for Stasis-Core bridge enter messages
2501  * \param data Passed on
2502  * \param sub The stasis subscription for this message callback
2503  * \param topic The topic this message was published for
2504  * \param message The message - hopefully a bridge one!
2505  */
2506 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2507                 struct stasis_message *message)
2508 {
2509         struct ast_bridge_blob *update = stasis_message_data(message);
2510         struct ast_bridge_snapshot *bridge = update->bridge;
2511         struct ast_channel_snapshot *channel = update->channel;
2512         RAII_VAR(struct cdr_object *, cdr,
2513                         ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY),
2514                         ao2_cleanup);
2515         RAII_VAR(struct module_config *, mod_cfg,
2516                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2517
2518         if (filter_bridge_messages(bridge)) {
2519                 return;
2520         }
2521
2522         if (filter_channel_snapshot(channel)) {
2523                 return;
2524         }
2525
2526         CDR_DEBUG(mod_cfg, "Bridge Enter message for channel %s: %u.%08u\n",
2527                         channel->name,
2528                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2529                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2530
2531         if (!cdr) {
2532                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2533                 ast_assert(0);
2534                 return;
2535         }
2536
2537         if (!strcmp(bridge->subclass, "parking")) {
2538                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2539         } else {
2540                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2541         }
2542 }
2543
2544 /*!
2545  * \brief Handler for when a channel is parked
2546  * \param data Passed on
2547  * \param sub The stasis subscription for this message callback
2548  * \param topic The topic this message was published for
2549  * \param message The message about who got parked
2550  * */
2551 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2552                 struct stasis_message *message)
2553 {
2554         struct ast_parked_call_payload *payload = stasis_message_data(message);
2555         struct ast_channel_snapshot *channel = payload->parkee;
2556         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
2557         RAII_VAR(struct module_config *, mod_cfg,
2558                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2559         int unhandled = 1;
2560         struct cdr_object *it_cdr;
2561
2562         /* Anything other than getting parked will be handled by other updates */
2563         if (payload->event_type != PARKED_CALL) {
2564                 return;
2565         }
2566
2567         /* No one got parked? */
2568         if (!channel) {
2569                 return;
2570         }
2571
2572         if (filter_channel_snapshot(channel)) {
2573                 return;
2574         }
2575
2576         CDR_DEBUG(mod_cfg, "Parked Call message for channel %s: %u.%08u\n",
2577                         channel->name,
2578                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2579                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2580
2581         cdr = ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY);
2582         if (!cdr) {
2583                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2584                 ast_assert(0);
2585                 return;
2586         }
2587
2588         ao2_lock(cdr);
2589
2590         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2591                 if (it_cdr->fn_table->process_parked_channel) {
2592                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2593                 }
2594         }
2595
2596         if (unhandled) {
2597                 /* Nothing handled the messgae - we need a new one! */
2598                 struct cdr_object *new_cdr = cdr_object_create_and_append(cdr);
2599                 if (new_cdr) {
2600                         /* As the new CDR is created in the single state, it is guaranteed
2601                          * to have a function for the parked call message and will handle
2602                          * the message */
2603                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2604                 }
2605         }
2606
2607         ao2_unlock(cdr);
2608
2609 }
2610
2611 /*!
2612  * \brief Handler for a synchronization message
2613  * \param data Passed on
2614  * \param sub The stasis subscription for this message callback
2615  * \param topic The topic this message was published for
2616  * \param message A blank ao2 object
2617  * */
2618 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2619                 struct stasis_message *message)
2620 {
2621         return;
2622 }
2623
2624 struct ast_cdr_config *ast_cdr_get_config(void)
2625 {
2626         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2627         ao2_ref(mod_cfg->general, +1);
2628         return mod_cfg->general;
2629 }
2630
2631 void ast_cdr_set_config(struct ast_cdr_config *config)
2632 {
2633         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2634
2635         ao2_cleanup(mod_cfg->general);
2636         mod_cfg->general = config;
2637         ao2_ref(mod_cfg->general, +1);
2638
2639         cdr_toggle_runtime_options();
2640 }
2641
2642 int ast_cdr_is_enabled(void)
2643 {
2644         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2645         return ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED);
2646 }
2647
2648 int ast_cdr_backend_suspend(const char *name)
2649 {
2650         int success = -1;
2651         struct cdr_beitem *i = NULL;
2652
2653         AST_RWLIST_WRLOCK(&be_list);
2654         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2655                 if (!strcasecmp(name, i->name)) {
2656                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2657                         i->suspended = 1;
2658                         success = 0;
2659                 }
2660         }
2661         AST_RWLIST_UNLOCK(&be_list);
2662
2663         return success;
2664 }
2665
2666 int ast_cdr_backend_unsuspend(const char *name)
2667 {
2668         int success = -1;
2669         struct cdr_beitem *i = NULL;
2670
2671         AST_RWLIST_WRLOCK(&be_list);
2672         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2673                 if (!strcasecmp(name, i->name)) {
2674                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2675                         i->suspended = 0;
2676                         success = 0;
2677                 }
2678         }
2679         AST_RWLIST_UNLOCK(&be_list);
2680
2681         return success;
2682 }
2683
2684 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2685 {
2686         struct cdr_beitem *i = NULL;
2687
2688         if (!name)
2689                 return -1;
2690
2691         if (!be) {
2692                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2693                 return -1;
2694         }
2695
2696         AST_RWLIST_WRLOCK(generic_list);
2697         AST_RWLIST_TRAVERSE(generic_list, i, list) {
2698                 if (!strcasecmp(name, i->name)) {
2699                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2700                         AST_RWLIST_UNLOCK(generic_list);
2701                         return -1;
2702                 }
2703         }
2704
2705         if (!(i = ast_calloc(1, sizeof(*i))))
2706                 return -1;
2707
2708         i->be = be;
2709         ast_copy_string(i->name, name, sizeof(i->name));
2710         ast_copy_string(i->desc, desc, sizeof(i->desc));
2711
2712         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2713         AST_RWLIST_UNLOCK(generic_list);
2714
2715         return 0;
2716 }
2717
2718 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2719 {
2720         return cdr_generic_register(&be_list, name, desc, be);
2721 }
2722
2723 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2724 {
2725         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2726 }
2727
2728 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2729 {
2730         struct cdr_beitem *match = NULL;
2731         int active_count;
2732
2733         AST_RWLIST_WRLOCK(generic_list);
2734         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2735                 if (!strcasecmp(name, match->name)) {
2736                         break;
2737                 }
2738         }
2739
2740         if (!match) {
2741                 AST_RWLIST_UNLOCK(generic_list);
2742                 return 0;
2743         }
2744
2745         active_count = ao2_container_count(active_cdrs_by_channel);
2746
2747         if (!match->suspended && active_count != 0) {
2748                 AST_RWLIST_UNLOCK(generic_list);
2749                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2750                         name, active_count);
2751                 return -1;
2752         }
2753
2754         AST_RWLIST_REMOVE(generic_list, match, list);
2755         AST_RWLIST_UNLOCK(generic_list);
2756
2757         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2758         ast_free(match);
2759
2760         return 0;
2761 }
2762
2763 int ast_cdr_unregister(const char *name)
2764 {
2765         return ast_cdr_generic_unregister(&be_list, name);
2766 }
2767
2768 int ast_cdr_modifier_unregister(const char *name)
2769 {
2770         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2771 }
2772
2773 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2774 {
2775         struct ast_cdr *newcdr;
2776
2777         if (!cdr) {
2778                 return NULL;
2779         }
2780         newcdr = ast_cdr_alloc();
2781         if (!newcdr) {
2782                 return NULL;
2783         }
2784
2785         *newcdr = *cdr;
2786         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2787         copy_variables(&newcdr->varshead, &cdr->varshead);
2788         newcdr->next = NULL;
2789
2790         return newcdr;
2791 }
2792
2793 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2794 {
2795         struct ast_var_t *variables;
2796
2797         if (ast_strlen_zero(name)) {
2798                 return NULL;
2799         }
2800
2801         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
2802                 if (!strcasecmp(name, ast_var_name(variables))) {
2803                         return ast_var_value(variables);
2804                 }
2805         }
2806
2807         return NULL;
2808 }
2809
2810 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
2811 {
2812         if (fmt == NULL) {      /* raw mode */
2813                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
2814         } else {
2815                 buf[0] = '\0';/* Ensure the buffer is initialized. */
2816                 if (when.tv_sec) {
2817                         struct ast_tm tm;
2818
2819                         ast_localtime(&when, &tm, NULL);
2820                         ast_strftime(buf, bufsize, fmt, &tm);
2821                 }
2822         }
2823 }
2824
2825 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
2826 {
2827         const char *fmt = "%Y-%m-%d %T";
2828         const char *varbuf;
2829
2830         if (!cdr) {
2831                 return;
2832         }
2833
2834         *ret = NULL;
2835
2836         if (!strcasecmp(name, "clid")) {
2837                 ast_copy_string(workspace, cdr->clid, workspacelen);
2838         } else if (!strcasecmp(name, "src")) {
2839                 ast_copy_string(workspace, cdr->src, workspacelen);
2840         } else if (!strcasecmp(name, "dst")) {
2841                 ast_copy_string(workspace, cdr->dst, workspacelen);
2842         } else if (!strcasecmp(name, "dcontext")) {
2843                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
2844         } else if (!strcasecmp(name, "channel")) {
2845                 ast_copy_string(workspace, cdr->channel, workspacelen);
2846         } else if (!strcasecmp(name, "dstchannel")) {
2847                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
2848         } else if (!strcasecmp(name, "lastapp")) {
2849                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
2850         } else if (!strcasecmp(name, "lastdata")) {
2851                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
2852         } else if (!strcasecmp(name, "start")) {
2853                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
2854         } else if (!strcasecmp(name, "answer")) {
2855                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
2856         } else if (!strcasecmp(name, "end")) {
2857                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
2858         } else if (!strcasecmp(name, "duration")) {
2859                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
2860         } else if (!strcasecmp(name, "billsec")) {
2861                 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);
2862         } else if (!strcasecmp(name, "disposition")) {
2863                 if (raw) {
2864                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
2865                 } else {
2866                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
2867                 }
2868         } else if (!strcasecmp(name, "amaflags")) {
2869                 if (raw) {
2870                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
2871                 } else {
2872                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
2873                 }
2874         } else if (!strcasecmp(name, "accountcode")) {
2875                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
2876         } else if (!strcasecmp(name, "peeraccount")) {
2877                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
2878         } else if (!strcasecmp(name, "uniqueid")) {
2879                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
2880         } else if (!strcasecmp(name, "linkedid")) {
2881                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
2882         } else if (!strcasecmp(name, "userfield")) {
2883                 ast_copy_string(workspace, cdr->userfield, workspacelen);
2884         } else if (!strcasecmp(name, "sequence")) {
2885                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
2886         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
2887                 ast_copy_string(workspace, varbuf, workspacelen);
2888         } else {
2889                 workspace[0] = '\0';
2890         }
2891
2892         if (!ast_strlen_zero(workspace)) {
2893                 *ret = workspace;
2894         }
2895 }
2896
2897 /*
2898  * \internal
2899  * \brief Callback that finds all CDRs that reference a particular channel by name
2900  */
2901 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
2902 {
2903         struct cdr_object *cdr = obj;
2904         const char *name = arg;
2905
2906         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
2907                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
2908                 return CMP_MATCH;
2909         }
2910         return 0;
2911 }
2912
2913 /*
2914  * \internal
2915  * \brief Callback that finds a CDR by channel name
2916  */
2917 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
2918 {
2919         struct cdr_object *cdr = obj;
2920         const char *name = arg;
2921
2922         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
2923                 return CMP_MATCH;
2924         }
2925         return 0;
2926 }
2927
2928 /* Read Only CDR variables */
2929 static const char * const cdr_readonly_vars[] = {
2930         "clid",
2931         "src",
2932         "dst",
2933         "dcontext",
2934         "channel",
2935         "dstchannel",
2936         "lastapp",
2937         "lastdata",
2938         "start",
2939         "answer",
2940         "end",
2941         "duration",
2942         "billsec",
2943         "disposition",
2944         "amaflags",
2945         "accountcode",
2946         "uniqueid",
2947         "linkedid",
2948         "userfield",
2949         "sequence",
2950         NULL
2951 };
2952
2953 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
2954 {
2955         struct cdr_object *cdr;
2956         struct cdr_object *it_cdr;
2957         struct ao2_iterator *it_cdrs;
2958         char *arg = ast_strdupa(channel_name);
2959         int x;
2960
2961         for (x = 0; cdr_readonly_vars[x]; x++) {
2962                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
2963                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
2964                         return -1;
2965                 }
2966         }
2967
2968         it_cdrs = ao2_callback(active_cdrs_by_channel, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
2969         if (!it_cdrs) {
2970                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
2971                 return -1;
2972         }
2973
2974         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
2975                 ao2_lock(cdr);
2976                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2977                         struct varshead *headp = NULL;
2978
2979                         if (it_cdr->fn_table == &finalized_state_fn_table) {
2980                                 continue;
2981                         }
2982                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
2983                                 headp = &it_cdr->party_a.variables;
2984                         } else if (it_cdr->party_b.snapshot
2985                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
2986                                 headp = &it_cdr->party_b.variables;
2987                         }
2988                         if (headp) {
2989                                 set_variable(headp, name, value);
2990                         }
2991                 }
2992         }
2993         ao2_iterator_destroy(it_cdrs);
2994
2995         return 0;
2996 }
2997
2998 /*!
2999  * \brief Format a variable on a \ref cdr_object
3000  */
3001 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3002 {
3003         struct ast_var_t *variable;
3004
3005         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3006                 if (!strcasecmp(name, ast_var_name(variable))) {
3007                         ast_copy_string(value, ast_var_value(variable), length);
3008                         return;
3009                 }
3010         }
3011
3012         *value = '\0';
3013 }
3014
3015 /*!
3016  * \brief Format one of the standard properties on a \ref cdr_object
3017  */
3018 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3019 {
3020         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3021         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3022
3023         if (!strcasecmp(name, "clid")) {
3024                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3025         } else if (!strcasecmp(name, "src")) {
3026                 ast_copy_string(value, party_a->caller_number, length);
3027         } else if (!strcasecmp(name, "dst")) {
3028                 ast_copy_string(value, party_a->exten, length);
3029         } else if (!strcasecmp(name, "dcontext")) {
3030                 ast_copy_string(value, party_a->context, length);
3031         } else if (!strcasecmp(name, "channel")) {
3032                 ast_copy_string(value, party_a->name, length);
3033         } else if (!strcasecmp(name, "dstchannel")) {
3034                 if (party_b) {
3035                         ast_copy_string(value, party_b->name, length);
3036                 } else {
3037                         ast_copy_string(value, "", length);
3038                 }
3039         } else if (!strcasecmp(name, "lastapp")) {
3040                 ast_copy_string(value, party_a->appl, length);
3041         } else if (!strcasecmp(name, "lastdata")) {
3042                 ast_copy_string(value, party_a->data, length);
3043         } else if (!strcasecmp(name, "start")) {
3044                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3045         } else if (!strcasecmp(name, "answer")) {
3046                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3047         } else if (!strcasecmp(name, "end")) {
3048                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3049         } else if (!strcasecmp(name, "duration")) {
3050                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3051         } else if (!strcasecmp(name, "billsec")) {
3052                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3053         } else if (!strcasecmp(name, "disposition")) {
3054                 snprintf(value, length, "%u", cdr_obj->disposition);
3055         } else if (!strcasecmp(name, "amaflags")) {
3056                 snprintf(value, length, "%d", party_a->amaflags);
3057         } else if (!strcasecmp(name, "accountcode")) {
3058                 ast_copy_string(value, party_a->accountcode, length);
3059         } else if (!strcasecmp(name, "peeraccount")) {
3060                 if (party_b) {
3061                         ast_copy_string(value, party_b->accountcode, length);
3062                 } else {
3063                         ast_copy_string(value, "", length);
3064                 }
3065         } else if (!strcasecmp(name, "uniqueid")) {
3066                 ast_copy_string(value, party_a->uniqueid, length);
3067         } else if (!strcasecmp(name, "linkedid")) {
3068                 ast_copy_string(value, cdr_obj->linkedid, length);
3069         } else if (!strcasecmp(name, "userfield")) {
3070                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3071         } else if (!strcasecmp(name, "sequence")) {
3072                 snprintf(value, length, "%u", cdr_obj->sequence);
3073         } else {
3074                 return 1;
3075         }
3076
3077         return 0;
3078 }
3079
3080 /*! \internal
3081  * \brief Look up and retrieve a CDR object by channel name
3082  * \param name The name of the channel
3083  * \retval NULL on error
3084  * \retval The \ref cdr_object for the channel on success, with the reference
3085  *      count bumped by one.
3086  */
3087 static struct cdr_object *cdr_object_get_by_name(const char *name)
3088 {
3089         char *param;
3090
3091         if (ast_strlen_zero(name)) {
3092                 return NULL;
3093         }
3094
3095         param = ast_strdupa(name);
3096         return ao2_callback(active_cdrs_by_channel, 0, cdr_object_get_by_name_cb, param);
3097 }
3098
3099 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3100 {
3101         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3102         struct cdr_object *cdr_obj;
3103
3104         if (!cdr) {
3105                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3106                 return 1;
3107         }
3108
3109         if (ast_strlen_zero(name)) {
3110                 return 1;
3111         }
3112
3113         ao2_lock(cdr);
3114
3115         cdr_obj = cdr->last;
3116         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3117                 /* Property failed; attempt variable */
3118                 cdr_object_format_var_internal(cdr_obj, name, value, length);
3119         }
3120
3121         ao2_unlock(cdr);
3122
3123         return 0;
3124 }
3125
3126 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3127 {
3128         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3129         struct cdr_object *it_cdr;
3130         struct ast_var_t *variable;
3131         const char *var;
3132         char workspace[256];
3133         int total = 0, x = 0, i;
3134
3135         if (!cdr) {
3136                 RAII_VAR(struct module_config *, mod_cfg,
3137                          ao2_global_obj_ref(module_configs), ao2_cleanup);
3138
3139                 if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3140                         ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3141                 }
3142
3143                 return 0;
3144         }
3145
3146         ast_str_reset(*buf);
3147
3148         ao2_lock(cdr);
3149         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3150                 if (++x > 1)
3151                         ast_str_append(buf, 0, "\n");
3152
3153                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3154                         if (!(var = ast_var_name(variable))) {
3155                                 continue;
3156                         }
3157
3158                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
3159                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3160                                 break;
3161                         }
3162
3163                         total++;
3164                 }
3165
3166                 for (i = 0; cdr_readonly_vars[i]; i++) {
3167                         if (cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace))) {
3168                                 /* Unhandled read-only CDR variable. */
3169                                 ast_assert(0);
3170                                 continue;
3171                         }
3172
3173                         if (!ast_strlen_zero(workspace)
3174                                 && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
3175                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3176                                 break;
3177                         }
3178                         total++;
3179                 }
3180         }
3181         ao2_unlock(cdr);
3182         return total;
3183 }
3184
3185 void ast_cdr_free(struct ast_cdr *cdr)
3186 {
3187         while (cdr) {
3188                 struct ast_cdr *next = cdr->next;
3189
3190                 free_variables(&cdr->varshead);
3191                 ast_free(cdr);
3192                 cdr = next;
3193         }
3194 }
3195
3196 struct ast_cdr *ast_cdr_alloc(void)
3197 {
3198         struct ast_cdr *x;
3199
3200         x = ast_calloc(1, sizeof(*x));
3201         return x;
3202 }
3203
3204 const char *ast_cdr_disp2str(int disposition)
3205 {
3206         switch (disposition) {
3207         case AST_CDR_NULL:
3208                 return "NO ANSWER"; /* by default, for backward compatibility */
3209         case AST_CDR_NOANSWER:
3210                 return "NO ANSWER";
3211         case AST_CDR_FAILED:
3212                 return "FAILED";
3213         case AST_CDR_BUSY:
3214                 return "BUSY";
3215         case AST_CDR_ANSWERED:
3216                 return "ANSWERED";
3217         case AST_CDR_CONGESTION:
3218                 return "CONGESTION";
3219         }
3220         return "UNKNOWN";
3221 }
3222
3223 struct party_b_userfield_update {
3224         const char *channel_name;
3225         const char *userfield;
3226 };
3227
3228 /*! \brief Callback used to update the userfield on Party B on all CDRs */
3229 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, int flags)
3230 {
3231         struct cdr_object *cdr = obj;
3232         struct party_b_userfield_update *info = arg;
3233         struct cdr_object *it_cdr;
3234         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3235                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3236                         continue;
3237                 }
3238                 if (it_cdr->party_b.snapshot
3239                         && !strcasecmp(it_cdr->party_b.snapshot->name, info->channel_name)) {
3240                         strcpy(it_cdr->party_b.userfield, info->userfield);
3241                 }
3242         }
3243         return 0;
3244 }
3245
3246 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
3247 {
3248         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3249         struct party_b_userfield_update party_b_info = {
3250                         .channel_name = channel_name,
3251                         .userfield = userfield,
3252         };
3253         struct cdr_object *it_cdr;
3254
3255         /* Handle Party A */
3256         if (cdr) {
3257                 ao2_lock(cdr);
3258                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3259                         if (it_cdr->fn_table == &finalized_state_fn_table) {
3260                                 continue;
3261                         }
3262                         strcpy(it_cdr->party_a.userfield, userfield);
3263                 }
3264                 ao2_unlock(cdr);
3265         }
3266
3267         /* Handle Party B */
3268         ao2_callback(active_cdrs_by_channel, OBJ_NODATA,
3269                         cdr_object_update_party_b_userfield_cb,
3270                         &party_b_info);
3271
3272 }
3273
3274 static void post_cdr(struct ast_cdr *cdr)
3275 {
3276         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3277         struct cdr_beitem *i;
3278
3279         for (; cdr ; cdr = cdr->next) {
3280                 /* For people, who don't want to see unanswered single-channel events */
3281                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
3282                                 cdr->disposition < AST_CDR_ANSWERED &&
3283                                 (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
3284                         ast_debug(1, "Skipping CDR  for %s since we weren't answered\n", cdr->channel);
3285                         continue;
3286                 }
3287
3288                 /* Modify CDR's */
3289                 AST_RWLIST_RDLOCK(&mo_list);
3290                 AST_RWLIST_TRAVERSE(&mo_list, i, list) {
3291                         i->be(cdr);
3292                 }
3293                 AST_RWLIST_UNLOCK(&mo_list);
3294
3295                 if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
3296                         continue;
3297                 }
3298                 AST_RWLIST_RDLOCK(&be_list);
3299                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
3300                         if (!i->suspended) {
3301                                 i->be(cdr);
3302                         }
3303                 }
3304                 AST_RWLIST_UNLOCK(&be_list);
3305         }
3306 }
3307
3308 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
3309 {
3310         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3311         struct cdr_object *it_cdr;
3312
3313         if (!cdr) {
3314                 return -1;
3315         }
3316
3317         ao2_lock(cdr);
3318         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3319                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3320                         continue;
3321                 }
3322                 /* Note: in general, set the flags on both the CDR record as well as the
3323                  * Party A. Sometimes all we have is the Party A to look at.
3324                  */
3325                 ast_set_flag(&it_cdr->flags, option);
3326                 ast_set_flag(&it_cdr->party_a, option);
3327         }
3328         ao2_unlock(cdr);
3329
3330         return 0;
3331 }
3332
3333 int ast_cdr_clear_property(const char *channel_name, enum ast_cdr_options option)
3334 {
3335         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3336         struct cdr_object *it_cdr;
3337
3338         if (!cdr) {
3339                 return -1;
3340         }
3341
3342         ao2_lock(cdr);
3343         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3344                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3345                         continue;
3346                 }
3347                 ast_clear_flag(&it_cdr->flags, option);
3348         }
3349         ao2_unlock(cdr);
3350
3351         return 0;
3352 }
3353
3354 int ast_cdr_reset(const char *channel_name, int keep_variables)
3355 {
3356         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3357         struct ast_var_t *vardata;
3358         struct cdr_object *it_cdr;
3359
3360         if (!cdr) {
3361                 return -1;
3362         }
3363
3364         ao2_lock(cdr);
3365         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3366                 /* clear variables */
3367                 if (!keep_variables) {
3368                         while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_a.variables, entries))) {
3369                                 ast_var_delete(vardata);
3370                         }
3371                         if (cdr->party_b.snapshot) {
3372                                 while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_b.variables, entries))) {
3373                                         ast_var_delete(vardata);
3374                                 }
3375                         }
3376                 }
3377
3378                 /* Reset to initial state */
3379                 memset(&it_cdr->start, 0, sizeof(it_cdr->start));
3380                 memset(&it_cdr->end, 0, sizeof(it_cdr->end));
3381                 memset(&it_cdr->answer, 0, sizeof(it_cdr->answer));
3382                 it_cdr->start = ast_tvnow();
3383                 cdr_object_check_party_a_answer(it_cdr);
3384         }
3385         ao2_unlock(cdr);
3386
3387         return 0;
3388 }
3389
3390 int ast_cdr_fork(const char *channel_name, struct ast_flags *options)
3391 {
3392         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3393         struct cdr_object *new_cdr;
3394         struct cdr_object *it_cdr;
3395         struct cdr_object *cdr_obj;
3396
3397         if (!cdr) {
3398                 return -1;
3399         }
3400
3401         {
3402                 SCOPED_AO2LOCK(lock, cdr);
3403
3404                 cdr_obj = cdr->last;
3405                 if (cdr_obj->fn_table == &finalized_state_fn_table) {
3406                         /* If the last CDR in the chain is finalized, don't allow a fork -
3407                          * things are already dying at this point
3408                          */
3409                         return -1;
3410                 }
3411
3412                 /* Copy over the basic CDR information. The Party A information is
3413                  * copied over automatically as part of the append
3414                  */
3415                 ast_debug(1, "Forking CDR for channel %s\n", cdr->party_a.snapshot->name);
3416                 new_cdr = cdr_object_create_and_append(cdr);
3417                 if (!new_cdr) {
3418                         return -1;
3419                 }
3420                 new_cdr->fn_table = cdr_obj->fn_table;
3421                 ast_string_field_set(new_cdr, bridge, cdr->bridge);
3422                 ast_string_field_set(new_cdr, appl, cdr->appl);
3423                 ast_string_field_set(new_cdr, data, cdr->data);
3424                 ast_string_field_set(new_cdr, context, cdr->context);
3425                 ast_string_field_set(new_cdr, exten, cdr->exten);
3426                 new_cdr->flags = cdr->flags;
3427                 /* Explicitly clear the AST_CDR_LOCK_APP flag - we want
3428                  * the application to be changed on the new CDR if the
3429                  * dialplan demands it
3430                  */
3431                 ast_clear_flag(&new_cdr->flags, AST_CDR_LOCK_APP);
3432
3433                 /* If there's a Party B, copy it over as well */
3434                 if (cdr_obj->party_b.snapshot) {
3435                         new_cdr->party_b.snapshot = cdr_obj->party_b.snapshot;
3436                         ao2_ref(new_cdr->party_b.snapshot, +1);
3437                         strcpy(new_cdr->party_b.userfield, cdr_obj->party_b.userfield);
3438                         new_cdr->party_b.flags = cdr_obj->party_b.flags;
3439                         if (ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3440                                 copy_variables(&new_cdr->party_b.variables, &cdr_obj->party_b.variables);
3441                         }
3442                 }
3443                 new_cdr->start = cdr_obj->start;
3444                 new_cdr->answer = cdr_obj->answer;
3445
3446                 /* Modify the times based on the flags passed in */
3447                 if (ast_test_flag(options, AST_CDR_FLAG_SET_ANSWER)
3448                                 && new_cdr->party_a.snapshot->state == AST_STATE_UP) {
3449                         new_cdr->answer = ast_tvnow();
3450                 }
3451                 if (ast_test_flag(options, AST_CDR_FLAG_RESET)) {
3452                         new_cdr->answer = ast_tvnow();
3453                         new_cdr->start = ast_tvnow();
3454                 }
3455
3456                 /* Create and append, by default, copies over the variables */
3457                 if (!ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3458                         free_variables(&new_cdr->party_a.variables);
3459                 }
3460
3461                 /* Finalize any current CDRs */
3462                 if (ast_test_flag(options, AST_CDR_FLAG_FINALIZE)) {
3463                         for (it_cdr = cdr; it_cdr != new_cdr; it_cdr = it_cdr->next) {
3464                                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3465                                         continue;
3466                                 }
3467                                 /* Force finalization on the CDR. This will bypass any checks for
3468                                  * end before 'h' extension.
3469                                  */
3470                                 cdr_object_finalize(it_cdr);
3471                                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
3472                         }
3473                 }
3474         }
3475
3476         return 0;
3477 }
3478
3479 /*! \note Don't call without cdr_batch_lock */
3480 static void reset_batch(void)
3481 {
3482         batch->size = 0;
3483         batch->head = NULL;
3484         batch->tail = NULL;
3485 }
3486
3487 /*! \note Don't call without cdr_batch_lock */
3488 static int init_batch(void)
3489 {
3490         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
3491         if (!(batch = ast_malloc(sizeof(*batch))))
3492                 return -1;
3493
3494         reset_batch();
3495
3496         return 0;
3497 }
3498
3499 static void *do_batch_backend_process(void *data)
3500 {
3501         struct cdr_batch_item *processeditem;
3502         struct cdr_batch_item *batchitem = data;
3503
3504         /* Push each CDR into storage mechanism(s) and free all the memory */
3505         while (batchitem) {
3506                 post_cdr(batchitem->cdr);
3507                 ast_cdr_free(batchitem->cdr);
3508                 processeditem = batchitem;
3509                 batchitem = batchitem->next;
3510                 ast_free(processeditem);
3511         }
3512
3513         return NULL;
3514 }
3515
3516 static void cdr_submit_batch(int do_shutdown)
3517 {
3518         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3519         struct cdr_batch_item *oldbatchitems = NULL;
3520         pthread_t batch_post_thread = AST_PTHREADT_NULL;
3521
3522         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
3523         if (!batch || !batch->head) {
3524                 return;
3525         }
3526
3527         /* move the old CDRs aside, and prepare a new CDR batch */
3528         ast_mutex_lock(&cdr_batch_lock);
3529         oldbatchitems = batch->head;
3530         reset_batch();
3531         ast_mutex_unlock(&cdr_batch_lock);
3532
3533         /* if configured, spawn a new thread to post these CDRs,
3534            also try to save as much as possible if we are shutting down safely */
3535         if (ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY) || do_shutdown) {
3536                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
3537                 do_batch_backend_process(oldbatchitems);
3538         } else {
3539                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
3540                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
3541                         do_batch_backend_process(oldbatchitems);
3542                 } else {
3543                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
3544                 }
3545         }
3546 }
3547
3548 static int submit_scheduled_batch(const void *data)
3549 {
3550         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3551         cdr_submit_batch(0);
3552         /* manually reschedule from this point in time */
3553
3554         ast_mutex_lock(&cdr_sched_lock);
3555         cdr_sched = ast_sched_add(sched, mod_cfg->general->batch_settings.time * 1000, submit_scheduled_batch, NULL);
3556         ast_mutex_unlock(&cdr_sched_lock);
3557         /* returning zero so the scheduler does not automatically reschedule */
3558         return 0;
3559 }
3560
3561 /*! Do not hold the batch lock while calling this function */
3562 static void submit_unscheduled_batch(void)
3563 {
3564         /* Prevent two deletes from happening at the same time */
3565         ast_mutex_lock(&cdr_sched_lock);
3566         /* this is okay since we are not being called from within the scheduler */
3567         AST_SCHED_DEL(sched, cdr_sched);
3568         /* schedule the submission to occur ASAP (1 ms) */
3569         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
3570         ast_mutex_unlock(&cdr_sched_lock);
3571
3572         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
3573         ast_mutex_lock(&cdr_pending_lock);
3574         ast_cond_signal(&cdr_pending_cond);
3575         ast_mutex_unlock(&cdr_pending_lock);
3576 }
3577
3578 static void cdr_detach(struct ast_cdr *cdr)
3579 {
3580         struct cdr_batch_item *newtail;
3581         int curr;
3582         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3583         int submit_batch = 0;
3584
3585         if (!cdr) {
3586                 return;
3587         }
3588
3589         /* maybe they disabled CDR stuff completely, so just drop it */
3590         if (!ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3591                 ast_debug(1, "Dropping CDR !\n");
3592                 ast_cdr_free(cdr);
3593                 return;
3594         }
3595
3596         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
3597         if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3598                 post_cdr(cdr);
3599                 ast_cdr_free(cdr);
3600                 return;
3601         }
3602
3603         /* otherwise, each CDR gets put into a batch list (at the end) */
3604         ast_debug(1, "CDR detaching from this thread\n");
3605
3606         /* we'll need a new tail for every CDR */
3607         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
3608                 post_cdr(cdr);
3609                 ast_cdr_free(cdr);
3610                 return;
3611         }
3612
3613         /* don't traverse a whole list (just keep track of the tail) */
3614         ast_mutex_lock(&cdr_batch_lock);
3615         if (!batch)
3616                 init_batch();
3617         if (!batch->head) {
3618                 /* new batch is empty, so point the head at the new tail */
3619                 batch->head = newtail;
3620         } else {
3621                 /* already got a batch with something in it, so just append a new tail */
3622                 batch->tail->next = newtail;
3623         }
3624         newtail->cdr = cdr;
3625         batch->tail = newtail;
3626         curr = batch->size++;
3627
3628         /* if we have enough stuff to post, then do it */
3629         if (curr >= (mod_cfg->general->batch_settings.size - 1)) {
3630                 submit_batch = 1;
3631         }
3632         ast_mutex_unlock(&cdr_batch_lock);
3633
3634         /* Don't call submit_unscheduled_batch with the cdr_batch_lock held */
3635         if (submit_batch) {
3636                 submit_unscheduled_batch();
3637         }
3638 }
3639
3640 static void *do_cdr(void *data)
3641 {
3642         struct timespec timeout;
3643         int schedms;
3644         int numevents = 0;
3645
3646         for (;;) {
3647                 struct timeval now;
3648                 schedms = ast_sched_wait(sched);
3649                 /* this shouldn't happen, but provide a 1 second default just in case */
3650                 if (schedms <= 0)
3651                         schedms = 1000;
3652                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
3653                 timeout.tv_sec = now.tv_sec;
3654                 timeout.tv_nsec = now.tv_usec * 1000;
3655                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
3656                 ast_mutex_lock(&cdr_pending_lock);
3657                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
3658                 numevents = ast_sched_runq(sched);
3659                 ast_mutex_unlock(&cdr_pending_lock);
3660                 ast_debug(2, "Processed %d scheduled CDR batches from the run queue\n", numevents);
3661         }
3662
3663         return NULL;
3664 }
3665
3666 static char *handle_cli_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3667 {
3668         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3669
3670         switch (cmd) {
3671         case CLI_INIT:
3672                 e->command = "cdr set debug [on|off]";
3673                 e->usage = "Enable or disable extra debugging in the CDR Engine. Note\n"
3674                                 "that this will dump debug information to the VERBOSE setting\n"
3675                                 "and should only be used when debugging information from the\n"
3676                                 "CDR engine is needed.\n";
3677                 return NULL;
3678         case CLI_GENERATE:
3679                 return NULL;
3680         }
3681
3682         if (a->argc != 4) {
3683                 return CLI_SHOWUSAGE;
3684         }
3685
3686         if (!strcasecmp(a->argv[3], "on")
3687                 && !ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3688                 ast_set_flag(&mod_cfg->general->settings, CDR_DEBUG);
3689                 ast_cli(a->fd, "CDR debugging enabled\n");
3690         } else if (!strcasecmp(a->argv[3], "off")
3691                 && ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3692                 ast_clear_flag(&mod_cfg->general->settings, CDR_DEBUG);
3693                 ast_cli(a->fd, "CDR debugging disabled\n");
3694         }
3695
3696         return CLI_SUCCESS;
3697 }
3698
3699 /*! \brief Complete user input for 'cdr show' */
3700 static char *cli_complete_show(struct ast_cli_args *a)
3701 {
3702         char *result = NULL;
3703         int wordlen = strlen(a->word);
3704         int which = 0;
3705         struct ao2_iterator it_cdrs;
3706         struct cdr_object *cdr;
3707
3708         it_cdrs = ao2_iterator_init(active_cdrs_by_channel, 0);
3709         while ((cdr = ao2_iterator_next(&it_cdrs))) {
3710                 if (!strncasecmp(a->word, cdr->party_a.snapshot->name, wordlen) &&
3711                         (++which > a->n)) {
3712                         result = ast_strdup(cdr->party_a.snapshot->name);
3713                         if (result) {
3714                                 ao2_ref(cdr, -1);
3715                                 break;
3716                         }
3717                 }
3718                 ao2_ref(cdr, -1);
3719         }
3720         ao2_iterator_destroy(&it_cdrs);
3721         return result;
3722 }
3723
3724 static void cli_show_channels(struct ast_cli_args *a)
3725 {
3726         struct ao2_iterator it_cdrs;
3727         struct cdr_object *cdr;
3728         char start_time_buffer[64];
3729         char answer_time_buffer[64];
3730         char end_time_buffer[64];
3731
3732 #define TITLE_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8s %-8.8s\n"
3733 #define FORMAT_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8ld %-8.8ld\n"
3734
3735         ast_cli(a->fd, "\n");
3736         ast_cli(a->fd, "Channels with Call Detail Record (CDR) Information\n");
3737         ast_cli(a->fd, "--------------------------------------------------\n");
3738         ast_cli(a->fd, TITLE_STRING, "Channel", "Dst. Channel", "LastApp", "Start", "Answer", "End", "Billsec", "Duration");
3739
3740         it_cdrs = ao2_iterator_init(active_cdrs_by_channel, 0);
3741         for (; (cdr = ao2_iterator_next(&it_cdrs)); ao2_cleanup(cdr)) {
3742                 struct cdr_object *it_cdr;
3743                 struct timeval start_time = { 0, };
3744                 struct timeval answer_time = { 0, };
3745                 struct timeval end_time = { 0, };
3746
3747                 SCOPED_AO2LOCK(lock, cdr);
3748
3749                 /* Calculate the start, end, answer, billsec, and duration over the
3750                  * life of all of the CDR entries
3751                  */
3752                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3753                         if (snapshot_is_dialed(it_cdr->party_a.snapshot)) {
3754                                 continue;
3755                         }
3756                         if (ast_tvzero(start_time)) {
3757                                 start_time = it_cdr->start;
3758                         }
3759                         if (!ast_tvzero(it_cdr->answer) && ast_tvzero(answer_time)) {
3760                                 answer_time = it_cdr->answer;
3761                         }
3762                 }
3763
3764                 /* If there was no start time, then all CDRs were for a dialed channel; skip */
3765                 if (ast_tvzero(start_time)) {
3766                         continue;
3767                 }
3768                 it_cdr = cdr->last;
3769
3770                 end_time = ast_tvzero(it_cdr->end) ? ast_tvnow() : it_cdr->end;
3771                 cdr_get_tv(start_time, "%T", start_time_buffer, sizeof(start_time_buffer));
3772                 cdr_get_tv(answer_time, "%T", answer_time_buffer, sizeof(answer_time_buffer));
3773                 cdr_get_tv(end_time, "%T", end_time_buffer, sizeof(end_time_buffer));
3774                 ast_cli(a->fd, FORMAT_STRING, it_cdr->party_a.snapshot->name,
3775                                 it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->name : "<none>",
3776                                 it_cdr->appl,
3777                                 start_time_buffer,
3778                                 answer_time_buffer,
3779                                 end_time_buffer,
3780                                 ast_tvzero(answer_time) ? 0 : (long)ast_tvdiff_ms(end_time, answer_time) / 1000,
3781                                 (long)ast_tvdiff_ms(end_time, start_time) / 1000);
3782         }
3783         ao2_iterator_destroy(&it_cdrs);
3784 #undef FORMAT_STRING
3785 #undef TITLE_STRING
3786 }
3787
3788 static void cli_show_channel(struct ast_cli_args *a)
3789<