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