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