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