main/cdr: Fixed cdr start overwriting
[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 with initiation flag
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_init(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table, int do_init)
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
810         if (cdr->fn_table->init_function && do_init) {
811                 cdr->fn_table->init_function(cdr);
812         }
813 }
814
815 /*!
816  * \brief Transition a \ref cdr_object to a new state
817  * \param cdr The \ref cdr_object to transition
818  * \param fn_table The \ref cdr_object_fn_table state to go to
819  */
820 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
821 {
822         cdr_object_transition_state_init(cdr, fn_table, 1);
823 }
824
825 /*!
826  * \internal
827  * \brief Hash function for master CDR container indexed by Party A uniqueid.
828  */
829 static int cdr_master_hash_fn(const void *obj, const int flags)
830 {
831         const struct cdr_object *cdr;
832         const char *key;
833
834         switch (flags & OBJ_SEARCH_MASK) {
835         case OBJ_SEARCH_KEY:
836                 key = obj;
837                 break;
838         case OBJ_SEARCH_OBJECT:
839                 cdr = obj;
840                 key = cdr->uniqueid;
841                 break;
842         default:
843                 ast_assert(0);
844                 return 0;
845         }
846         return ast_str_case_hash(key);
847 }
848
849 /*!
850  * \internal
851  * \brief Comparison function for master CDR container indexed by Party A uniqueid.
852  */
853 static int cdr_master_cmp_fn(void *obj, void *arg, int flags)
854 {
855     struct cdr_object *left = obj;
856     struct cdr_object *right = arg;
857     const char *right_key = arg;
858     int cmp;
859
860     switch (flags & OBJ_SEARCH_MASK) {
861     case OBJ_SEARCH_OBJECT:
862         right_key = right->uniqueid;
863         /* Fall through */
864     case OBJ_SEARCH_KEY:
865         cmp = strcmp(left->uniqueid, right_key);
866         break;
867     case OBJ_SEARCH_PARTIAL_KEY:
868         /*
869          * We could also use a partial key struct containing a length
870          * so strlen() does not get called for every comparison instead.
871          */
872         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
873         break;
874     default:
875         /* Sort can only work on something with a full or partial key. */
876         ast_assert(0);
877         cmp = 0;
878         break;
879     }
880     return cmp ? 0 : CMP_MATCH;
881 }
882
883 /*!
884  * \internal
885  * \brief Hash function for all CDR container indexed by Party B channel name.
886  */
887 static int cdr_all_hash_fn(const void *obj, const int flags)
888 {
889         const struct cdr_object *cdr;
890         const char *key;
891
892         switch (flags & OBJ_SEARCH_MASK) {
893         case OBJ_SEARCH_KEY:
894                 key = obj;
895                 break;
896         case OBJ_SEARCH_OBJECT:
897                 cdr = obj;
898                 key = cdr->party_b_name;
899                 break;
900         default:
901                 ast_assert(0);
902                 return 0;
903         }
904         return ast_str_case_hash(key);
905 }
906
907 /*!
908  * \internal
909  * \brief Comparison function for all CDR container indexed by Party B channel name.
910  */
911 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
912 {
913     struct cdr_object *left = obj;
914     struct cdr_object *right = arg;
915     const char *right_key = arg;
916     int cmp;
917
918     switch (flags & OBJ_SEARCH_MASK) {
919     case OBJ_SEARCH_OBJECT:
920         right_key = right->party_b_name;
921         /* Fall through */
922     case OBJ_SEARCH_KEY:
923         cmp = strcasecmp(left->party_b_name, right_key);
924         break;
925     case OBJ_SEARCH_PARTIAL_KEY:
926         /*
927          * We could also use a partial key struct containing a length
928          * so strlen() does not get called for every comparison instead.
929          */
930         cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
931         break;
932     default:
933         /* Sort can only work on something with a full or partial key. */
934         ast_assert(0);
935         cmp = 0;
936         break;
937     }
938     return cmp ? 0 : CMP_MATCH;
939 }
940
941 /*!
942  * \internal
943  * \brief Relink the CDR because Party B's snapshot changed.
944  * \since 13.19.0
945  *
946  * \return Nothing
947  */
948 static void cdr_all_relink(struct cdr_object *cdr)
949 {
950         ao2_lock(active_cdrs_all);
951         if (cdr->party_b.snapshot) {
952                 if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->base->name)) {
953                         ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
954                         ast_string_field_set(cdr, party_b_name, cdr->party_b.snapshot->base->name);
955                         ao2_link_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
956                 }
957         } else {
958                 ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
959                 ast_string_field_set(cdr, party_b_name, "");
960         }
961         ao2_unlock(active_cdrs_all);
962 }
963
964 /*!
965  * \internal
966  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
967  * \since 13.19.0
968  *
969  * \return Nothing
970  */
971 static void cdr_all_unlink(struct cdr_object *cdr)
972 {
973         struct cdr_object *cur;
974         struct cdr_object *next;
975
976         ast_assert(cdr->is_root);
977
978         /* Hold a ref to the root CDR to ensure the list members don't go away on us. */
979         ao2_ref(cdr, +1);
980         ao2_lock(active_cdrs_all);
981         for (cur = cdr; cur; cur = next) {
982                 next = cur->next;
983                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
984                 /*
985                  * It is safe to still use cur after unlinking because the
986                  * root CDR holds a ref to all the CDRs in the list and we
987                  * have a ref to the root CDR.
988                  */
989                 ast_string_field_set(cur, party_b_name, "");
990         }
991         ao2_unlock(active_cdrs_all);
992         ao2_ref(cdr, -1);
993 }
994
995 /*!
996  * \brief \ref cdr_object Destructor
997  */
998 static void cdr_object_dtor(void *obj)
999 {
1000         struct cdr_object *cdr = obj;
1001         struct ast_var_t *it_var;
1002
1003         ao2_cleanup(cdr->party_a.snapshot);
1004         ao2_cleanup(cdr->party_b.snapshot);
1005         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
1006                 ast_var_delete(it_var);
1007         }
1008         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
1009                 ast_var_delete(it_var);
1010         }
1011         ast_string_field_free_memory(cdr);
1012
1013         /* CDR destruction used to work by calling ao2_cleanup(next) and
1014          * allowing the chain to destroy itself neatly. Unfortunately, for
1015          * really long chains, this can result in a stack overflow. So now
1016          * when the root CDR is destroyed, it is responsible for unreffing
1017          * all CDRs in the chain
1018          */
1019         if (cdr->is_root) {
1020                 struct cdr_object *curr = cdr->next;
1021                 struct cdr_object *next;
1022
1023                 while (curr) {
1024                         next = curr->next;
1025                         ao2_cleanup(curr);
1026                         curr = next;
1027                 }
1028         }
1029 }
1030
1031 /*!
1032  * \brief \ref cdr_object constructor
1033  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1034  *
1035  * This implicitly sets the state of the newly created CDR to the Single state
1036  * (\ref single_state_fn_table)
1037  */
1038 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
1039 {
1040         struct cdr_object *cdr;
1041
1042         ast_assert(chan != NULL);
1043
1044         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1045         if (!cdr) {
1046                 return NULL;
1047         }
1048         cdr->last = cdr;
1049         if (ast_string_field_init(cdr, 64)) {
1050                 ao2_cleanup(cdr);
1051                 return NULL;
1052         }
1053         ast_string_field_set(cdr, uniqueid, chan->base->uniqueid);
1054         ast_string_field_set(cdr, name, chan->base->name);
1055         ast_string_field_set(cdr, linkedid, chan->peer->linkedid);
1056         cdr->disposition = AST_CDR_NULL;
1057         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1058
1059         cdr->party_a.snapshot = chan;
1060         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1061
1062         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->base->name);
1063
1064         cdr_object_transition_state(cdr, &single_state_fn_table);
1065
1066         return cdr;
1067 }
1068
1069 /*!
1070  * \brief Create a new \ref cdr_object and append it to an existing chain
1071  * \param cdr The \ref cdr_object to append to
1072  */
1073 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
1074 {
1075         struct cdr_object *new_cdr;
1076         struct cdr_object *it_cdr;
1077         struct cdr_object *cdr_last;
1078
1079         cdr_last = cdr->last;
1080         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
1081         if (!new_cdr) {
1082                 return NULL;
1083         }
1084         new_cdr->disposition = AST_CDR_NULL;
1085
1086         /* Copy over the linkedid, as it may have changed */
1087         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1088         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1089         ast_string_field_set(new_cdr, data, cdr_last->data);
1090         ast_string_field_set(new_cdr, context, cdr_last->context);
1091         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1092
1093         /*
1094          * If the current CDR says to disable all future ones,
1095          * keep the disable chain going
1096          */
1097         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1098                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1099         }
1100
1101         /* Copy over other Party A information */
1102         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1103
1104         /* Append the CDR to the end of the list */
1105         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1106                 it_cdr->last = new_cdr;
1107         }
1108         it_cdr->last = new_cdr;
1109         it_cdr->next = new_cdr;
1110
1111         return new_cdr;
1112 }
1113
1114 /*!
1115  * \internal
1116  * \brief Determine if CDR flag is configured.
1117  *
1118  * \param cdr_flag The configured CDR flag to check.
1119  *
1120  * \retval 0 if the CDR flag is not configured.
1121  * \retval non-zero if the CDR flag is configured.
1122  *
1123  * \return Nothing
1124  */
1125 static int is_cdr_flag_set(unsigned int cdr_flag)
1126 {
1127         struct module_config *mod_cfg;
1128         int flag_set;
1129
1130         mod_cfg = ao2_global_obj_ref(module_configs);
1131         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1132         ao2_cleanup(mod_cfg);
1133         return flag_set;
1134 }
1135
1136 /*!
1137  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1138  * to endbeforehexten logic
1139  *
1140  * \param old_snapshot The previous state
1141  * \param new_snapshot The new state
1142  *
1143  * \retval 0 if the state has not changed
1144  * \retval 1 if the state changed
1145  */
1146 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1147         struct ast_channel_snapshot *new_snapshot)
1148 {
1149         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1150         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1151                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1152                 return 0;
1153         }
1154
1155         /* When Party A is originated to an application and the application exits, the stack
1156          * will attempt to clear the application and restore the dummy originate application
1157          * of "AppDialX". Ignore application changes to AppDialX as a result.
1158          */
1159         if (strcmp(new_snapshot->dialplan->appl, old_snapshot->dialplan->appl)
1160                 && strncasecmp(new_snapshot->dialplan->appl, "appdial", 7)
1161                 && (strcmp(new_snapshot->dialplan->context, old_snapshot->dialplan->context)
1162                         || strcmp(new_snapshot->dialplan->exten, old_snapshot->dialplan->exten)
1163                         || new_snapshot->dialplan->priority != old_snapshot->dialplan->priority)) {
1164                 return 1;
1165         }
1166
1167         return 0;
1168 }
1169
1170 /*!
1171  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1172  * that was created as the result of a dial operation
1173  *
1174  * \retval 0 the channel was not created as the result of a dial
1175  * \retval 1 the channel was created as the result of a dial
1176  */
1177 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1178 {
1179         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1180                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1181 }
1182
1183 /*!
1184  * \brief Given two CDR snapshots, figure out who should be Party A for the
1185  * resulting CDR
1186  * \param left One of the snapshots
1187  * \param right The other snapshot
1188  * \retval The snapshot that won
1189  */
1190 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1191 {
1192         /* Check whether or not the party is dialed. A dialed party is never the
1193          * Party A with a party that was not dialed.
1194          */
1195         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1196                 return left;
1197         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1198                 return right;
1199         }
1200
1201         /* Try the Party A flag */
1202         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1203                 return left;
1204         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1205                 return right;
1206         }
1207
1208         /* Neither party is dialed and neither has the Party A flag - defer to
1209          * creation time */
1210         if (left->snapshot->base->creationtime.tv_sec < right->snapshot->base->creationtime.tv_sec) {
1211                 return left;
1212         } else if (left->snapshot->base->creationtime.tv_sec > right->snapshot->base->creationtime.tv_sec) {
1213                 return right;
1214         } else if (left->snapshot->base->creationtime.tv_usec > right->snapshot->base->creationtime.tv_usec) {
1215                 return right;
1216         } else {
1217                 /* Okay, fine, take the left one */
1218                 return left;
1219         }
1220 }
1221
1222 /*!
1223  * Compute the duration for a \ref cdr_object
1224  */
1225 static long cdr_object_get_duration(struct cdr_object *cdr)
1226 {
1227         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1228 }
1229
1230 /*!
1231  * \brief Compute the billsec for a \ref cdr_object
1232  */
1233 static long cdr_object_get_billsec(struct cdr_object *cdr)
1234 {
1235         long int ms;
1236
1237         if (ast_tvzero(cdr->answer)) {
1238                 return 0;
1239         }
1240
1241         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1242         if (ms % 1000 >= 500
1243                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1244                 ms = (ms / 1000) + 1;
1245         } else {
1246                 ms = ms / 1000;
1247         }
1248
1249         return ms;
1250 }
1251
1252 /*!
1253  * \internal
1254  * \brief Set a variable on a CDR object
1255  *
1256  * \param headp The header pointer to the variable to set
1257  * \param name The name of the variable
1258  * \param value The value of the variable
1259  */
1260 static void set_variable(struct varshead *headp, const char *name, const char *value)
1261 {
1262         struct ast_var_t *newvariable;
1263
1264         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1265                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1266                         AST_LIST_REMOVE_CURRENT(entries);
1267                         ast_var_delete(newvariable);
1268                         break;
1269                 }
1270         }
1271         AST_LIST_TRAVERSE_SAFE_END;
1272
1273         if (value && (newvariable = ast_var_assign(name, value))) {
1274                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1275         }
1276 }
1277
1278 /*!
1279  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1280  * suitable for consumption by the registered CDR backends
1281  * \param cdr The \ref cdr_object to convert to a public record
1282  * \retval A chain of \ref ast_cdr objects on success
1283  * \retval NULL on failure
1284  */
1285 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1286 {
1287         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1288         struct cdr_object *it_cdr;
1289         struct ast_var_t *it_var, *it_copy_var;
1290         struct ast_channel_snapshot *party_a;
1291         struct ast_channel_snapshot *party_b;
1292
1293         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1294                 struct ast_cdr *cdr_copy;
1295
1296                 /* Don't create records for CDRs where the party A was a dialed channel */
1297                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1298                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1299                                 it_cdr->party_a.snapshot->base->name);
1300                         continue;
1301                 }
1302
1303                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1304                 if (!cdr_copy) {
1305                         ast_free(pub_cdr);
1306                         return NULL;
1307                 }
1308
1309                 party_a = it_cdr->party_a.snapshot;
1310                 party_b = it_cdr->party_b.snapshot;
1311
1312                 /* Party A */
1313                 ast_assert(party_a != NULL);
1314                 ast_copy_string(cdr_copy->accountcode, party_a->base->accountcode, sizeof(cdr_copy->accountcode));
1315                 cdr_copy->amaflags = party_a->amaflags;
1316                 ast_copy_string(cdr_copy->channel, party_a->base->name, sizeof(cdr_copy->channel));
1317                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller->name, party_a->caller->number, "");
1318                 ast_copy_string(cdr_copy->src, party_a->caller->number, sizeof(cdr_copy->src));
1319                 ast_copy_string(cdr_copy->uniqueid, party_a->base->uniqueid, sizeof(cdr_copy->uniqueid));
1320                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1321                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1322                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1323                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1324
1325                 /* Party B */
1326                 if (party_b) {
1327                         ast_copy_string(cdr_copy->dstchannel, party_b->base->name, sizeof(cdr_copy->dstchannel));
1328                         ast_copy_string(cdr_copy->peeraccount, party_b->base->accountcode, sizeof(cdr_copy->peeraccount));
1329                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1330                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1331                         }
1332                 }
1333                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1334                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1335                 }
1336
1337                 /* Timestamps/durations */
1338                 cdr_copy->start = it_cdr->start;
1339                 cdr_copy->answer = it_cdr->answer;
1340                 cdr_copy->end = it_cdr->end;
1341                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1342                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1343
1344                 /* Flags and IDs */
1345                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1346                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1347                 cdr_copy->disposition = it_cdr->disposition;
1348                 cdr_copy->sequence = it_cdr->sequence;
1349
1350                 /* Variables */
1351                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1352                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1353                         int found = 0;
1354                         struct ast_var_t *newvariable;
1355                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1356                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1357                                         found = 1;
1358                                         break;
1359                                 }
1360                         }
1361                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1362                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1363                         }
1364                 }
1365
1366                 if (!pub_cdr) {
1367                         pub_cdr = cdr_copy;
1368                         cdr_prev = pub_cdr;
1369                 } else {
1370                         cdr_prev->next = cdr_copy;
1371                         cdr_prev = cdr_copy;
1372                 }
1373         }
1374
1375         return pub_cdr;
1376 }
1377
1378 /*!
1379  * \brief Dispatch a CDR.
1380  * \param cdr The \ref cdr_object to dispatch
1381  *
1382  * This will create a \ref ast_cdr object and publish it to the various backends
1383  */
1384 static void cdr_object_dispatch(struct cdr_object *cdr)
1385 {
1386         struct ast_cdr *pub_cdr;
1387
1388         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1389                 cdr->party_a.snapshot->base->name,
1390                 cdr->party_b.snapshot ? cdr->party_b.snapshot->base->name : "<none>");
1391         pub_cdr = cdr_object_create_public_records(cdr);
1392         cdr_detach(pub_cdr);
1393 }
1394
1395 /*!
1396  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1397  * \param cdr The \ref cdr_object
1398  * \param hangupcause The Asterisk hangup cause code
1399  */
1400 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1401 {
1402         /* Change the disposition based on the hang up cause */
1403         switch (hangupcause) {
1404         case AST_CAUSE_BUSY:
1405                 cdr->disposition = AST_CDR_BUSY;
1406                 break;
1407         case AST_CAUSE_CONGESTION:
1408                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1409                         cdr->disposition = AST_CDR_FAILED;
1410                 } else {
1411                         cdr->disposition = AST_CDR_CONGESTION;
1412                 }
1413                 break;
1414         case AST_CAUSE_NO_ROUTE_DESTINATION:
1415         case AST_CAUSE_UNREGISTERED:
1416                 cdr->disposition = AST_CDR_FAILED;
1417                 break;
1418         case AST_CAUSE_NORMAL_CLEARING:
1419         case AST_CAUSE_NO_ANSWER:
1420                 cdr->disposition = AST_CDR_NOANSWER;
1421                 break;
1422         default:
1423                 break;
1424         }
1425 }
1426
1427 /*!
1428  * \brief Finalize a CDR.
1429  *
1430  * This function is safe to call multiple times. Note that you can call this
1431  * explicitly before going to the finalized state if there's a chance the CDR
1432  * will be re-activated, in which case the \ref cdr_object's end time should be
1433  * cleared. This function is implicitly called when a CDR transitions to the
1434  * finalized state and right before it is dispatched
1435  *
1436  * \param cdr_object The CDR to finalize
1437  */
1438 static void cdr_object_finalize(struct cdr_object *cdr)
1439 {
1440         if (!ast_tvzero(cdr->end)) {
1441                 return;
1442         }
1443         cdr->end = ast_tvnow();
1444
1445         if (cdr->disposition == AST_CDR_NULL) {
1446                 if (!ast_tvzero(cdr->answer)) {
1447                         cdr->disposition = AST_CDR_ANSWERED;
1448                 } else if (cdr->party_a.snapshot->hangup->cause) {
1449                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangup->cause);
1450                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangup->cause) {
1451                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangup->cause);
1452                 } else {
1453                         cdr->disposition = AST_CDR_FAILED;
1454                 }
1455         }
1456
1457         /* tv_usec is suseconds_t, which could be int or long */
1458         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1459                         cdr->party_a.snapshot->base->name,
1460                         (long)cdr->start.tv_sec,
1461                         (long)cdr->start.tv_usec,
1462                         (long)cdr->answer.tv_sec,
1463                         (long)cdr->answer.tv_usec,
1464                         (long)cdr->end.tv_sec,
1465                         (long)cdr->end.tv_usec,
1466                         ast_cdr_disp2str(cdr->disposition));
1467 }
1468
1469 /*!
1470  * \brief Check to see if a CDR needs to move to the finalized state because
1471  * its Party A hungup.
1472  */
1473 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1474 {
1475         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1476                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1477                 cdr_object_finalize(cdr);
1478         }
1479
1480         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1481                 && cdr->fn_table != &finalized_state_fn_table) {
1482                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1483         }
1484 }
1485
1486 /*!
1487  * \brief Check to see if a CDR needs to be answered based on its Party A.
1488  * Note that this is safe to call as much as you want - we won't answer twice
1489  */
1490 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1491 {
1492         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1493                 cdr->answer = ast_tvnow();
1494                 /* tv_usec is suseconds_t, which could be int or long */
1495                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1496                         (long)cdr->answer.tv_sec,
1497                         (long)cdr->answer.tv_usec);
1498         }
1499 }
1500
1501 /* \brief Set Caller ID information on a CDR */
1502 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1503 {
1504         if (!old_snapshot->snapshot) {
1505                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1506                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1507                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1508                 return;
1509         }
1510         if (strcmp(old_snapshot->snapshot->caller->dnid, new_snapshot->caller->dnid)) {
1511                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1512         }
1513         if (strcmp(old_snapshot->snapshot->caller->subaddr, new_snapshot->caller->subaddr)) {
1514                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1515         }
1516         if (strcmp(old_snapshot->snapshot->caller->dialed_subaddr, new_snapshot->caller->dialed_subaddr)) {
1517                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1518         }
1519 }
1520
1521 /*!
1522  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1523  * a new \ref ast_channel_snapshot
1524  * \param old_snapshot The old \ref cdr_object_snapshot
1525  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1526  */
1527 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1528                 struct ast_channel_snapshot *new_snapshot)
1529 {
1530         cdr_object_update_cid(old_snapshot, new_snapshot);
1531         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1532 }
1533
1534 /* BASE METHOD IMPLEMENTATIONS */
1535
1536 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1537 {
1538         ast_assert(strcasecmp(snapshot->base->name, cdr->party_a.snapshot->base->name) == 0);
1539
1540         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1541         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1542                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1543                 cdr_object_finalize(cdr);
1544                 return 0;
1545         }
1546
1547         /*
1548          * Only record the context and extension if we aren't in a subroutine, or if
1549          * we are executing hangup logic.
1550          */
1551         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1552                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1553                 if (strcmp(cdr->context, snapshot->dialplan->context)) {
1554                         ast_string_field_set(cdr, context, snapshot->dialplan->context);
1555                 }
1556                 if (strcmp(cdr->exten, snapshot->dialplan->exten)) {
1557                         ast_string_field_set(cdr, exten, snapshot->dialplan->exten);
1558                 }
1559         }
1560
1561         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1562
1563         /* When Party A is originated to an application and the application exits, the stack
1564          * will attempt to clear the application and restore the dummy originate application
1565          * of "AppDialX". Prevent that, and any other application changes we might not want
1566          * here.
1567          */
1568         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1569                 && !ast_strlen_zero(snapshot->dialplan->appl)
1570                 && (strncasecmp(snapshot->dialplan->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1571                 if (strcmp(cdr->appl, snapshot->dialplan->appl)) {
1572                         ast_string_field_set(cdr, appl, snapshot->dialplan->appl);
1573                 }
1574                 if (strcmp(cdr->data, snapshot->dialplan->data)) {
1575                         ast_string_field_set(cdr, data, snapshot->dialplan->data);
1576                 }
1577
1578                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1579                  * execute before the dial begins, will alter the application/data to
1580                  * something people typically don't want to see, if we see a channel enter
1581                  * into Dial here, we set the appl/data accordingly and lock it.
1582                  */
1583                 if (!strcmp(snapshot->dialplan->appl, "Dial")) {
1584                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1585                 }
1586         }
1587
1588         if (strcmp(cdr->linkedid, snapshot->peer->linkedid)) {
1589                 ast_string_field_set(cdr, linkedid, snapshot->peer->linkedid);
1590         }
1591         cdr_object_check_party_a_answer(cdr);
1592         cdr_object_check_party_a_hangup(cdr);
1593
1594         return 0;
1595 }
1596
1597 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1598 {
1599         return 0;
1600 }
1601
1602 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1603 {
1604         return 0;
1605 }
1606
1607 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1608 {
1609         /* Base process bridge enter simply indicates that we can't handle it */
1610         return BRIDGE_ENTER_NEED_CDR;
1611 }
1612
1613 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1614 {
1615         char park_info[128];
1616
1617         ast_assert(!strcasecmp(parking_info->parkee->base->name, cdr->party_a.snapshot->base->name));
1618
1619         /* Update Party A information regardless */
1620         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1621
1622         /* Fake out where we're parked */
1623         ast_string_field_set(cdr, appl, "Park");
1624         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1625         ast_string_field_set(cdr, data, park_info);
1626
1627         /* Prevent any further changes to the App/Data fields for this record */
1628         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1629
1630         return 0;
1631 }
1632
1633 /* SINGLE STATE */
1634
1635 static void single_state_init_function(struct cdr_object *cdr)
1636 {
1637         cdr->start = ast_tvnow();
1638         cdr_object_check_party_a_answer(cdr);
1639 }
1640
1641 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1642 {
1643         /* This should never happen! */
1644         ast_assert(cdr->party_b.snapshot == NULL);
1645         ast_assert(0);
1646         return;
1647 }
1648
1649 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1650 {
1651         if (caller && !strcasecmp(cdr->party_a.snapshot->base->name, caller->base->name)) {
1652                 base_process_party_a(cdr, caller);
1653                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1654                         cdr->party_a.snapshot->base->name);
1655                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1656                 cdr_all_relink(cdr);
1657                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1658                         cdr->party_b.snapshot->base->name);
1659
1660                 /* If we have two parties, lock the application that caused the
1661                  * two parties to be associated. This prevents mid-call event
1662                  * macros/gosubs from perturbing the CDR application/data
1663                  */
1664                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1665         } else if (!strcasecmp(cdr->party_a.snapshot->base->name, peer->base->name)) {
1666                 /* We're the entity being dialed, i.e., outbound origination */
1667                 base_process_party_a(cdr, peer);
1668                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1669                         cdr->party_a.snapshot->base->name);
1670         }
1671
1672         cdr_object_transition_state(cdr, &dial_state_fn_table);
1673         return 0;
1674 }
1675
1676 /*!
1677  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1678  * already in the bridge while in the Single state. The goal of this is to find
1679  * a Party B for our CDR.
1680  *
1681  * \param cdr Our \ref cdr_object in the Single state
1682  * \param cand_cdr The \ref cdr_object already in the Bridge state
1683  *
1684  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1685  * Party B
1686  * \retval 1 No party in the cand_cdr could be used as our Party B
1687  */
1688 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1689                 struct cdr_object *cand_cdr)
1690 {
1691         struct cdr_object_snapshot *party_a;
1692
1693         /* Don't match on ourselves */
1694         if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1695                 return 1;
1696         }
1697
1698         /* Try the candidate CDR's Party A first */
1699         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1700         if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1701                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1702                         cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name);
1703                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1704                 cdr_all_relink(cdr);
1705                 if (!cand_cdr->party_b.snapshot) {
1706                         /* We just stole them - finalize their CDR. Note that this won't
1707                          * transition their state, it just sets the end time and the
1708                          * disposition - if we need to re-activate them later, we can.
1709                          */
1710                         cdr_object_finalize(cand_cdr);
1711                 }
1712                 return 0;
1713         }
1714
1715         /* Try their Party B, unless it's us */
1716         if (!cand_cdr->party_b.snapshot
1717                 || !strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name)) {
1718                 return 1;
1719         }
1720         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1721         if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1722                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1723                         cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name);
1724                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1725                 cdr_all_relink(cdr);
1726                 return 0;
1727         }
1728
1729         return 1;
1730 }
1731
1732 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)
1733 {
1734         struct ao2_iterator it_cdrs;
1735         char *channel_id;
1736         int success = 0;
1737
1738         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1739
1740         if (ao2_container_count(bridge->channels) == 1) {
1741                 /* No one in the bridge yet but us! */
1742                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1743                 return BRIDGE_ENTER_ONLY_PARTY;
1744         }
1745
1746         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1747                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1748                 ao2_ref(channel_id, -1)) {
1749                 struct cdr_object *cand_cdr_master;
1750                 struct cdr_object *cand_cdr;
1751
1752                 cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1753                 if (!cand_cdr_master) {
1754                         continue;
1755                 }
1756
1757                 ao2_lock(cand_cdr_master);
1758                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1759                         /* Skip any records that are not in a bridge or in this bridge.
1760                          * I'm not sure how that would happen, but it pays to be careful. */
1761                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1762                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1763                                 continue;
1764                         }
1765
1766                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1767                                 continue;
1768                         }
1769                         /* We successfully got a party B - break out */
1770                         success = 1;
1771                         break;
1772                 }
1773                 ao2_unlock(cand_cdr_master);
1774                 ao2_cleanup(cand_cdr_master);
1775         }
1776         ao2_iterator_destroy(&it_cdrs);
1777
1778         /* We always transition state, even if we didn't get a peer */
1779         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1780
1781         /* Success implies that we have a Party B */
1782         if (success) {
1783                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1784         }
1785
1786         return BRIDGE_ENTER_NO_PARTY_B;
1787 }
1788
1789 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1790 {
1791         cdr_object_transition_state(cdr, &parked_state_fn_table);
1792         return 0;
1793 }
1794
1795
1796 /* DIAL STATE */
1797
1798 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1799 {
1800         ast_assert(snapshot != NULL);
1801         ast_assert(cdr->party_b.snapshot
1802                 && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
1803
1804         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1805
1806         /* If party B hangs up, finalize this CDR */
1807         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1808                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1809         }
1810 }
1811
1812 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1813 {
1814         /* Don't process a begin dial here. A party A already in the dial state will
1815          * who receives a dial begin for something else will be handled by the
1816          * message router callback and will add a new CDR for the party A */
1817         return 1;
1818 }
1819
1820 /*!
1821  * \internal
1822  * \brief Convert a dial status to a CDR disposition
1823  */
1824 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1825 {
1826         if (!strcmp(dial_status, "ANSWER")) {
1827                 return AST_CDR_ANSWERED;
1828         } else if (!strcmp(dial_status, "BUSY")) {
1829                 return AST_CDR_BUSY;
1830         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1831                 return AST_CDR_NOANSWER;
1832         } else if (!strcmp(dial_status, "CONGESTION")) {
1833                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1834                         return AST_CDR_FAILED;
1835                 } else {
1836                         return AST_CDR_CONGESTION;
1837                 }
1838         } else if (!strcmp(dial_status, "FAILED")) {
1839                 return AST_CDR_FAILED;
1840         }
1841         return AST_CDR_FAILED;
1842 }
1843
1844 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)
1845 {
1846         struct ast_channel_snapshot *party_a;
1847
1848         if (caller) {
1849                 party_a = caller;
1850         } else {
1851                 party_a = peer;
1852         }
1853         ast_assert(!strcasecmp(cdr->party_a.snapshot->base->name, party_a->base->name));
1854         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1855
1856         if (cdr->party_b.snapshot) {
1857                 if (strcasecmp(cdr->party_b.snapshot->base->name, peer->base->name)) {
1858                         /* Not the status for this CDR - defer back to the message router */
1859                         return 1;
1860                 }
1861                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1862         }
1863
1864         /* Set the disposition based on the dial string. */
1865         cdr->disposition = dial_status_to_disposition(dial_status);
1866         if (cdr->disposition == AST_CDR_ANSWERED) {
1867                 /* Switch to dial pending to wait and see what the caller does */
1868                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1869         } else {
1870                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1871         }
1872
1873         return 0;
1874 }
1875
1876 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)
1877 {
1878         int success = 0;
1879
1880         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1881
1882         /* Get parties in the bridge */
1883         if (ao2_container_count(bridge->channels) == 1) {
1884                 /* No one in the bridge yet but us! */
1885                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1886                 return BRIDGE_ENTER_ONLY_PARTY;
1887         }
1888
1889         /* If we don't have a Party B (originated channel), skip it */
1890         if (cdr->party_b.snapshot) {
1891                 struct ao2_iterator it_cdrs;
1892                 char *channel_id;
1893
1894                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1895                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1896                         ao2_ref(channel_id, -1)) {
1897                         struct cdr_object *cand_cdr_master;
1898                         struct cdr_object *cand_cdr;
1899
1900                         cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1901                         if (!cand_cdr_master) {
1902                                 continue;
1903                         }
1904
1905                         ao2_lock(cand_cdr_master);
1906                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1907                                 /* Skip any records that are not in a bridge or in this bridge.
1908                                  * I'm not sure how that would happen, but it pays to be careful. */
1909                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1910                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1911                                         continue;
1912                                 }
1913
1914                                 /* Skip any records that aren't our Party B */
1915                                 if (strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1916                                         continue;
1917                                 }
1918                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1919                                 /* If they have a Party B, they joined up with someone else as their
1920                                  * Party A. Don't finalize them as they're active. Otherwise, we
1921                                  * have stolen them so they need to be finalized.
1922                                  */
1923                                 if (!cand_cdr->party_b.snapshot) {
1924                                         cdr_object_finalize(cand_cdr);
1925                                 }
1926                                 success = 1;
1927                                 break;
1928                         }
1929                         ao2_unlock(cand_cdr_master);
1930                         ao2_cleanup(cand_cdr_master);
1931                 }
1932                 ao2_iterator_destroy(&it_cdrs);
1933         }
1934
1935         /* We always transition state, even if we didn't get a peer */
1936         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1937
1938         /* Success implies that we have a Party B */
1939         if (success) {
1940                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1941         }
1942         return BRIDGE_ENTER_NO_PARTY_B;
1943 }
1944
1945 /* DIALED PENDING STATE */
1946
1947 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1948 {
1949         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1950          * that means we need a new CDR; otherwise, switch us over to single.
1951          */
1952         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1953                 if (cdr->party_b.snapshot) {
1954                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1955                         cdr->fn_table->process_party_a(cdr, snapshot);
1956                         return 1;
1957                 } else {
1958                         /* The CDR does not need to be reinitialized when transitioning
1959                          * to its single state as this would overwrite the start time,
1960                          * causing potentially both the answer and the start time to be
1961                          * the same which is incorrect.
1962                          */
1963                         cdr_object_transition_state_init(cdr, &single_state_fn_table, 0);
1964                         cdr->fn_table->process_party_a(cdr, snapshot);
1965                         return 0;
1966                 }
1967         }
1968         base_process_party_a(cdr, snapshot);
1969         return 0;
1970 }
1971
1972 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)
1973 {
1974         cdr_object_transition_state(cdr, &dial_state_fn_table);
1975         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1976 }
1977
1978 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1979 {
1980         if (cdr->party_b.snapshot) {
1981                 /* We can't handle this as we have a Party B - ask for a new one */
1982                 return 1;
1983         }
1984         cdr_object_transition_state(cdr, &parked_state_fn_table);
1985         return 0;
1986 }
1987
1988 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1989 {
1990         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1991
1992         /* Ask for a new CDR */
1993         return 1;
1994 }
1995
1996 /* BRIDGE STATE */
1997
1998 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1999 {
2000         ast_assert(cdr->party_b.snapshot
2001                 && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
2002
2003         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
2004
2005         /* If party B hangs up, finalize this CDR */
2006         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
2007                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
2008         }
2009 }
2010
2011 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2012 {
2013         if (strcmp(cdr->bridge, bridge->uniqueid)) {
2014                 return 1;
2015         }
2016         if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)
2017                 && cdr->party_b.snapshot
2018                 && strcasecmp(cdr->party_b.snapshot->base->name, channel->base->name)) {
2019                 return 1;
2020         }
2021         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2022
2023         return 0;
2024 }
2025
2026 /* PARKED STATE */
2027
2028 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2029 {
2030         if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)) {
2031                 return 1;
2032         }
2033         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2034
2035         return 0;
2036 }
2037
2038 /* FINALIZED STATE */
2039
2040 static void finalized_state_init_function(struct cdr_object *cdr)
2041 {
2042         cdr_object_finalize(cdr);
2043 }
2044
2045 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2046 {
2047         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2048                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2049                 return 0;
2050         }
2051
2052         /* Indicate that, if possible, we should get a new CDR */
2053         return 1;
2054 }
2055
2056 /*!
2057  * \internal
2058  * \brief Filter channel snapshots by technology
2059  */
2060 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2061 {
2062         return snapshot->base->tech_properties & AST_CHAN_TP_INTERNAL;
2063 }
2064
2065 /*!
2066  * \internal
2067  * \brief Filter a channel snapshot update
2068  */
2069 static int filter_channel_snapshot_message(struct ast_channel_snapshot *old_snapshot,
2070                 struct ast_channel_snapshot *new_snapshot)
2071 {
2072         int ret = 0;
2073
2074         /* Drop cache updates from certain channel technologies */
2075         if (old_snapshot) {
2076                 ret |= filter_channel_snapshot(old_snapshot);
2077         }
2078         if (new_snapshot) {
2079                 ret |= filter_channel_snapshot(new_snapshot);
2080         }
2081
2082         return ret;
2083 }
2084
2085 static int dial_status_end(const char *dialstatus)
2086 {
2087         return (strcmp(dialstatus, "RINGING") &&
2088                         strcmp(dialstatus, "PROCEEDING") &&
2089                         strcmp(dialstatus, "PROGRESS"));
2090 }
2091
2092 /* TOPIC ROUTER CALLBACKS */
2093
2094 /*!
2095  * \brief Handler for Stasis-Core dial messages
2096  * \param data Passed on
2097  * \param sub The stasis subscription for this message callback
2098  * \param topic The topic this message was published for
2099  * \param message The message
2100  */
2101 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2102 {
2103         struct cdr_object *cdr;
2104         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2105         struct ast_channel_snapshot *caller;
2106         struct ast_channel_snapshot *peer;
2107         struct cdr_object *it_cdr;
2108         struct ast_json *dial_status_blob;
2109         const char *dial_status = NULL;
2110         int res = 1;
2111
2112         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2113         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2114         if (!peer && !caller) {
2115                 return;
2116         }
2117
2118         if (peer && filter_channel_snapshot(peer)) {
2119                 return;
2120         }
2121
2122         if (caller && filter_channel_snapshot(caller)) {
2123                 return;
2124         }
2125
2126         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2127         if (dial_status_blob) {
2128                 dial_status = ast_json_string_get(dial_status_blob);
2129         }
2130
2131         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2132                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2133                 caller ? caller->base->name : "(none)",
2134                 peer ? peer->base->name : "(none)",
2135                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2136                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2137
2138         /* Figure out who is running this show */
2139         if (caller) {
2140                 cdr = ao2_find(active_cdrs_master, caller->base->uniqueid, OBJ_SEARCH_KEY);
2141         } else {
2142                 cdr = ao2_find(active_cdrs_master, peer->base->uniqueid, OBJ_SEARCH_KEY);
2143         }
2144         if (!cdr) {
2145                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->base->name : peer->base->name);
2146                 ast_assert(0);
2147                 return;
2148         }
2149
2150         ao2_lock(cdr);
2151         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2152                 if (ast_strlen_zero(dial_status)) {
2153                         if (!it_cdr->fn_table->process_dial_begin) {
2154                                 continue;
2155                         }
2156                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2157                                 it_cdr,
2158                                 caller ? caller->base->name : "(none)",
2159                                 peer ? peer->base->name : "(none)");
2160                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2161                                         caller,
2162                                         peer);
2163                 } else if (dial_status_end(dial_status)) {
2164                         if (!it_cdr->fn_table->process_dial_end) {
2165                                 continue;
2166                         }
2167                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2168                                 it_cdr,
2169                                 caller ? caller->base->name : "(none)",
2170                                 peer ? peer->base->name : "(none)");
2171                         it_cdr->fn_table->process_dial_end(it_cdr,
2172                                         caller,
2173                                         peer,
2174                                         dial_status);
2175                 }
2176         }
2177
2178         /* If no CDR handled a dial begin message, make a new one */
2179         if (res && ast_strlen_zero(dial_status)) {
2180                 struct cdr_object *new_cdr;
2181
2182                 new_cdr = cdr_object_create_and_append(cdr);
2183                 if (new_cdr) {
2184                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2185                 }
2186         }
2187         ao2_unlock(cdr);
2188         ao2_cleanup(cdr);
2189 }
2190
2191 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2192 {
2193         struct cdr_object *cdr = obj;
2194
2195         if (!strcasecmp(cdr->party_b_name, arg)) {
2196 #ifdef AST_DEVMODE
2197                 struct ast_channel_snapshot *party_b = data;
2198
2199                 /*
2200                  * For sanity's sake we also assert the party_b snapshot
2201                  * is consistent with the key.
2202                  */
2203                 ast_assert(cdr->party_b.snapshot
2204                         && !strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name));
2205 #endif
2206
2207                 /* Don't transition to the finalized state - let the Party A do
2208                  * that when its ready
2209                  */
2210                 cdr_object_finalize(cdr);
2211         }
2212         return 0;
2213 }
2214
2215 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2216 {
2217         struct cdr_object *cdr = obj;
2218
2219         if (cdr->fn_table->process_party_b
2220                 && !strcasecmp(cdr->party_b_name, arg)) {
2221                 struct ast_channel_snapshot *party_b = data;
2222
2223                 /*
2224                  * For sanity's sake we also check the party_b snapshot
2225                  * for consistency with the key.  The callback needs and
2226                  * asserts the snapshot to be this way.
2227                  */
2228                 if (!cdr->party_b.snapshot
2229                         || strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name)) {
2230                         ast_log(LOG_NOTICE,
2231                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2232                                 cdr->linkedid,
2233                                 cdr->party_a.snapshot->base->name,
2234                                 cdr->party_b_name);
2235                         return 0;
2236                 }
2237
2238                 cdr->fn_table->process_party_b(cdr, party_b);
2239         }
2240         return 0;
2241 }
2242
2243 /*! \brief Determine if we need to add a new CDR based on snapshots */
2244 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2245                 struct ast_channel_snapshot *new_snapshot)
2246 {
2247         /* If we're dead, we don't need a new CDR */
2248         if (!new_snapshot
2249                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2250                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2251                 return 0;
2252         }
2253
2254         /* Auto-fall through will increment the priority but have no application */
2255         if (ast_strlen_zero(new_snapshot->dialplan->appl)) {
2256                 return 0;
2257         }
2258
2259         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2260                 return 0;
2261         }
2262
2263         return 1;
2264 }
2265
2266 /*!
2267  * \brief Handler for channel snapshot update messages
2268  * \param data Passed on
2269  * \param sub The stasis subscription for this message callback
2270  * \param topic The topic this message was published for
2271  * \param message The message
2272  */
2273 static void handle_channel_snapshot_update_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2274 {
2275         struct cdr_object *cdr;
2276         struct ast_channel_snapshot_update *update = stasis_message_data(message);
2277         struct cdr_object *it_cdr;
2278
2279         if (filter_channel_snapshot_message(update->old_snapshot, update->new_snapshot)) {
2280                 return;
2281         }
2282
2283         if (update->new_snapshot && !update->old_snapshot) {
2284                 cdr = cdr_object_alloc(update->new_snapshot);
2285                 if (!cdr) {
2286                         return;
2287                 }
2288                 cdr->is_root = 1;
2289                 ao2_link(active_cdrs_master, cdr);
2290         } else {
2291                 cdr = ao2_find(active_cdrs_master, update->new_snapshot->base->uniqueid, OBJ_SEARCH_KEY);
2292         }
2293
2294         /* Handle Party A */
2295         if (!cdr) {
2296                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", update->new_snapshot->base->name);
2297                 ast_assert(0);
2298         } else {
2299                 int all_reject = 1;
2300
2301                 ao2_lock(cdr);
2302                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2303                         if (!it_cdr->fn_table->process_party_a) {
2304                                 continue;
2305                         }
2306                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, update->new_snapshot);
2307                 }
2308                 if (all_reject && check_new_cdr_needed(update->old_snapshot, update->new_snapshot)) {
2309                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2310                         struct cdr_object *new_cdr;
2311
2312                         new_cdr = cdr_object_create_and_append(cdr);
2313                         if (new_cdr) {
2314                                 new_cdr->fn_table->process_party_a(new_cdr, update->new_snapshot);
2315                         }
2316                 }
2317                 ao2_unlock(cdr);
2318         }
2319
2320         if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2321                 ao2_lock(cdr);
2322                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, update->old_snapshot->base->name);
2323                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2324                         cdr_object_finalize(it_cdr);
2325                 }
2326                 cdr_object_dispatch(cdr);
2327                 ao2_unlock(cdr);
2328
2329                 cdr_all_unlink(cdr);
2330                 ao2_unlink(active_cdrs_master, cdr);
2331         }
2332
2333         /* Handle Party B */
2334         if (update->new_snapshot) {
2335                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2336                         cdr_object_update_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2337         }
2338
2339         if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2340                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2341                         cdr_object_finalize_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2342         }
2343
2344         ao2_cleanup(cdr);
2345 }
2346
2347 struct bridge_leave_data {
2348         struct ast_bridge_snapshot *bridge;
2349         struct ast_channel_snapshot *channel;
2350 };
2351
2352 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2353 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2354 {
2355         struct cdr_object *cdr = obj;
2356         struct bridge_leave_data *leave_data = data;
2357
2358         if (cdr->fn_table == &bridge_state_fn_table
2359                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2360                 && !strcasecmp(cdr->party_b_name, arg)) {
2361                 /*
2362                  * For sanity's sake we also assert the party_b snapshot
2363                  * is consistent with the key.
2364                  */
2365                 ast_assert(cdr->party_b.snapshot
2366                         && !strcasecmp(cdr->party_b.snapshot->base->name, leave_data->channel->base->name));
2367
2368                 /* It is our Party B, in our bridge. Set the end time and let the handler
2369                  * transition our CDR appropriately when we leave the bridge.
2370                  */
2371                 cdr_object_finalize(cdr);
2372         }
2373         return 0;
2374 }
2375
2376 /*! \brief Filter bridge messages based on bridge technology */
2377 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2378 {
2379         /* Ignore holding bridge technology messages. We treat this simply as an application
2380          * that a channel enters into.
2381          */
2382         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2383                 return 1;
2384         }
2385         return 0;
2386 }
2387
2388 /*!
2389  * \brief Handler for when a channel leaves a bridge
2390  * \param data Passed on
2391  * \param sub The stasis subscription for this message callback
2392  * \param topic The topic this message was published for
2393  * \param message The message - hopefully a bridge one!
2394  */
2395 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2396                 struct stasis_message *message)
2397 {
2398         struct ast_bridge_blob *update = stasis_message_data(message);
2399         struct ast_bridge_snapshot *bridge = update->bridge;
2400         struct ast_channel_snapshot *channel = update->channel;
2401         struct cdr_object *cdr;
2402         struct cdr_object *it_cdr;
2403         struct bridge_leave_data leave_data = {
2404                 .bridge = bridge,
2405                 .channel = channel,
2406         };
2407         int left_bridge = 0;
2408
2409         if (filter_bridge_messages(bridge)) {
2410                 return;
2411         }
2412
2413         if (filter_channel_snapshot(channel)) {
2414                 return;
2415         }
2416
2417         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2418                 channel->base->name,
2419                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2420                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2421
2422         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2423         if (!cdr) {
2424                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2425                 ast_assert(0);
2426                 return;
2427         }
2428
2429         /* Party A */
2430         ao2_lock(cdr);
2431         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2432                 if (!it_cdr->fn_table->process_bridge_leave) {
2433                         continue;
2434                 }
2435                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2436                         it_cdr, channel->base->name);
2437                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2438                         ast_string_field_set(it_cdr, bridge, "");
2439                         left_bridge = 1;
2440                 }
2441         }
2442         ao2_unlock(cdr);
2443
2444         /* Party B */
2445         if (left_bridge
2446                 && strcmp(bridge->subclass, "parking")) {
2447                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2448                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->base->name,
2449                         &leave_data);
2450         }
2451
2452         ao2_cleanup(cdr);
2453 }
2454
2455 /*!
2456  * \internal
2457  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2458  *
2459  * \note The new CDR will be automatically transitioned to the bridge state
2460  */
2461 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2462                 struct cdr_object_snapshot *party_b)
2463 {
2464         struct cdr_object *new_cdr;
2465
2466         new_cdr = cdr_object_create_and_append(cdr);
2467         if (!new_cdr) {
2468                 return;
2469         }
2470         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2471         cdr_all_relink(new_cdr);
2472         cdr_object_check_party_a_answer(new_cdr);
2473         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2474         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2475         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2476                 new_cdr, new_cdr->party_a.snapshot->base->name,
2477                 party_b->snapshot->base->name);
2478 }
2479
2480 /*!
2481  * \brief Process a single \ref bridge_candidate
2482  *
2483  * When a CDR enters a bridge, it needs to make pairings with everyone else
2484  * that it is not currently paired with. This function determines, for the
2485  * CDR for the channel that entered the bridge and the CDR for every other
2486  * channel currently in the bridge, who is Party A and makes new CDRs.
2487  *
2488  * \param cdr The \ref cdr_obj being processed
2489  * \param cand_cdr The \ref cdr_object that is a candidate
2490  *
2491  */
2492 static void bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2493 {
2494         struct cdr_object_snapshot *party_a;
2495         struct cdr_object *cand_cdr;
2496
2497         ao2_lock(base_cand_cdr);
2498
2499         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2500                 /* Skip any records that are not in this bridge */
2501                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2502                         continue;
2503                 }
2504
2505                 /* If the candidate is us or someone we've taken on, pass on by */
2506                 if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)
2507                         || (cdr->party_b.snapshot
2508                                 && !strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name))) {
2509                         break;
2510                 }
2511
2512                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2513                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2514                  * Party B */
2515                 if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2516                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2517                         break;
2518                 }
2519
2520                 /* We're Party B. Check if we can add ourselves immediately or if we need
2521                  * a new CDR for them (they already have a Party B) */
2522                 if (cand_cdr->party_b.snapshot
2523                         && strcasecmp(cand_cdr->party_b.snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2524                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2525                 } else {
2526                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2527                                 cand_cdr, cand_cdr->party_a.snapshot->base->name,
2528                                 cdr->party_a.snapshot->base->name);
2529                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2530                         cdr_all_relink(cand_cdr);
2531                         /* It's possible that this joined at one point and was never chosen
2532                          * as party A. Clear their end time, as it would be set in such a
2533                          * case.
2534                          */
2535                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2536                 }
2537
2538                 break;
2539         }
2540
2541         ao2_unlock(base_cand_cdr);
2542 }
2543
2544 /*!
2545  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2546  * entered a bridge
2547  * \param cdr The \ref cdr_object that just entered the bridge
2548  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2549  */
2550 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2551 {
2552         struct ao2_iterator it_channels;
2553         char *channel_id;
2554
2555         it_channels = ao2_iterator_init(bridge->channels, 0);
2556         while ((channel_id = ao2_iterator_next(&it_channels))) {
2557                 struct cdr_object *cand_cdr;
2558
2559                 cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2560                 if (cand_cdr) {
2561                         bridge_candidate_process(cdr, cand_cdr);
2562                         ao2_ref(cand_cdr, -1);
2563                 }
2564
2565                 ao2_ref(channel_id, -1);
2566         }
2567         ao2_iterator_destroy(&it_channels);
2568 }
2569
2570 /*! \brief Handle entering into a parking bridge
2571  * \param cdr The CDR to operate on
2572  * \param bridge The bridge the channel just entered
2573  * \param channel The channel snapshot
2574  */
2575 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2576                 struct ast_bridge_snapshot *bridge,
2577                 struct ast_channel_snapshot *channel)
2578 {
2579         int res = 1;
2580         struct cdr_object *it_cdr;
2581         struct cdr_object *new_cdr;
2582
2583         ao2_lock(cdr);
2584
2585         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2586                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2587                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2588                 }
2589                 if (it_cdr->fn_table->process_party_a) {
2590                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2591                                 channel->base->name);
2592                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2593                 }
2594         }
2595
2596         if (res) {
2597                 /* No one handled it - we need a new one! */
2598                 new_cdr = cdr_object_create_and_append(cdr);
2599                 if (new_cdr) {
2600                         /* Let the single state transition us to Parked */
2601                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2602                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2603                 }
2604         }
2605         ao2_unlock(cdr);
2606 }
2607
2608 /*! \brief Handle a bridge enter message for a 'normal' bridge
2609  * \param cdr The CDR to operate on
2610  * \param bridge The bridge the channel just entered
2611  * \param channel The channel snapshot
2612  */
2613 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2614                 struct ast_bridge_snapshot *bridge,
2615                 struct ast_channel_snapshot *channel)
2616 {
2617         enum process_bridge_enter_results result;
2618         struct cdr_object *it_cdr;
2619         struct cdr_object *new_cdr;
2620         struct cdr_object *handled_cdr = NULL;
2621
2622         ao2_lock(cdr);
2623
2624 try_again:
2625         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2626                 if (it_cdr->fn_table->process_party_a) {
2627                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2628                                 channel->base->name);
2629                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2630                 }
2631
2632                 /* Notify all states that they have entered a bridge */
2633                 if (it_cdr->fn_table->process_bridge_enter) {
2634                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2635                                 channel->base->name);
2636                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2637                         switch (result) {
2638                         case BRIDGE_ENTER_ONLY_PARTY:
2639                                 /* Fall through */
2640                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2641                                 if (!handled_cdr) {
2642                                         handled_cdr = it_cdr;
2643                                 }
2644                                 break;
2645                         case BRIDGE_ENTER_NEED_CDR:
2646                                 /* Pass */
2647                                 break;
2648                         case BRIDGE_ENTER_NO_PARTY_B:
2649                                 /* We didn't win on any - end this CDR. If someone else comes in later
2650                                  * that is Party B to this CDR, it can re-activate this CDR.
2651                                  */
2652                                 if (!handled_cdr) {
2653                                         handled_cdr = it_cdr;
2654                                 }
2655                                 cdr_object_finalize(cdr);
2656                                 break;
2657                         }
2658                 }
2659         }
2660
2661         /* Create the new matchings, but only for either:
2662          *  * The first CDR in the chain that handled it. This avoids issues with
2663          *    forked CDRs.
2664          *  * If no one handled it, the last CDR in the chain. This would occur if
2665          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2666          *    to make pairings with everyone in the bridge.
2667          */
2668         if (handled_cdr) {
2669                 handle_bridge_pairings(handled_cdr, bridge);
2670         } else {
2671                 /* Nothing handled it - we need a new one! */
2672                 new_cdr = cdr_object_create_and_append(cdr);
2673                 if (new_cdr) {
2674                         /* This is guaranteed to succeed: the new CDR is created in the single state
2675                          * and will be able to handle the bridge enter message
2676                          */
2677                         goto try_again;
2678                 }
2679         }
2680         ao2_unlock(cdr);
2681 }
2682
2683 /*!
2684  * \internal
2685  * \brief Handler for Stasis-Core bridge enter messages
2686  * \param data Passed on
2687  * \param sub The stasis subscription for this message callback
2688  * \param topic The topic this message was published for
2689  * \param message The message - hopefully a bridge one!
2690  */
2691 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2692                 struct stasis_message *message)
2693 {
2694         struct ast_bridge_blob *update = stasis_message_data(message);
2695         struct ast_bridge_snapshot *bridge = update->bridge;
2696         struct ast_channel_snapshot *channel = update->channel;
2697         struct cdr_object *cdr;
2698
2699         if (filter_bridge_messages(bridge)) {
2700                 return;
2701         }
2702
2703         if (filter_channel_snapshot(channel)) {
2704                 return;
2705         }
2706
2707         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2708                 channel->base->name,
2709                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2710                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2711
2712         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2713         if (!cdr) {
2714                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2715                 ast_assert(0);
2716                 return;
2717         }
2718
2719         if (!strcmp(bridge->subclass, "parking")) {
2720                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2721         } else {
2722                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2723         }
2724         ao2_cleanup(cdr);
2725 }
2726
2727 /*!
2728  * \brief Handler for when a channel is parked
2729  * \param data Passed on
2730  * \param sub The stasis subscription for this message callback
2731  * \param topic The topic this message was published for
2732  * \param message The message about who got parked
2733  * */
2734 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2735                 struct stasis_message *message)
2736 {
2737         struct ast_parked_call_payload *payload = stasis_message_data(message);
2738         struct ast_channel_snapshot *channel = payload->parkee;
2739         struct cdr_object *cdr;
2740         int unhandled = 1;
2741         struct cdr_object *it_cdr;
2742
2743         /* Anything other than getting parked will be handled by other updates */
2744         if (payload->event_type != PARKED_CALL) {
2745                 return;
2746         }
2747
2748         /* No one got parked? */
2749         if (!channel) {
2750                 return;
2751         }
2752
2753         if (filter_channel_snapshot(channel)) {
2754                 return;
2755         }
2756
2757         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2758                 channel->base->name,
2759                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2760                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2761
2762         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2763         if (!cdr) {
2764                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2765                 ast_assert(0);
2766                 return;
2767         }
2768
2769         ao2_lock(cdr);
2770
2771         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2772                 if (it_cdr->fn_table->process_parked_channel) {
2773                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2774                 }
2775         }
2776
2777         if (unhandled) {
2778                 /* Nothing handled the messgae - we need a new one! */
2779                 struct cdr_object *new_cdr;
2780
2781                 new_cdr = cdr_object_create_and_append(cdr);
2782                 if (new_cdr) {
2783                         /* As the new CDR is created in the single state, it is guaranteed
2784                          * to have a function for the parked call message and will handle
2785                          * the message */
2786                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2787                 }
2788         }
2789
2790         ao2_unlock(cdr);
2791
2792         ao2_cleanup(cdr);
2793 }
2794
2795 /*!
2796  * \brief Handler for a synchronization message
2797  * \param data Passed on
2798  * \param sub The stasis subscription for this message callback
2799  * \param topic The topic this message was published for
2800  * \param message A blank ao2 object
2801  * */
2802 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2803                 struct stasis_message *message)
2804 {
2805         return;
2806 }
2807
2808 struct ast_cdr_config *ast_cdr_get_config(void)
2809 {
2810         struct ast_cdr_config *general;
2811         struct module_config *mod_cfg;
2812
2813         mod_cfg = ao2_global_obj_ref(module_configs);
2814         if (!mod_cfg) {
2815                 return NULL;
2816         }
2817         general = ao2_bump(mod_cfg->general);
2818         ao2_cleanup(mod_cfg);
2819         return general;
2820 }
2821
2822 void ast_cdr_set_config(struct ast_cdr_config *config)
2823 {
2824         struct module_config *mod_cfg;
2825
2826         if (!config) {
2827                 return;
2828         }
2829
2830         mod_cfg = ao2_global_obj_ref(module_configs);
2831         if (!mod_cfg) {
2832                 return;
2833         }
2834
2835         ao2_replace(mod_cfg->general, config);
2836
2837         cdr_set_debug_mode(mod_cfg);
2838         cdr_toggle_runtime_options();
2839
2840         ao2_cleanup(mod_cfg);
2841 }
2842
2843 int ast_cdr_is_enabled(void)
2844 {
2845         return is_cdr_flag_set(CDR_ENABLED);
2846 }
2847
2848 int ast_cdr_backend_suspend(const char *name)
2849 {
2850         int success = -1;
2851         struct cdr_beitem *i = NULL;
2852
2853         AST_RWLIST_WRLOCK(&be_list);
2854         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2855                 if (!strcasecmp(name, i->name)) {
2856                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2857                         i->suspended = 1;
2858                         success = 0;
2859                 }
2860         }
2861         AST_RWLIST_UNLOCK(&be_list);
2862
2863         return success;
2864 }
2865
2866 int ast_cdr_backend_unsuspend(const char *name)
2867 {
2868         int success = -1;
2869         struct cdr_beitem *i = NULL;
2870
2871         AST_RWLIST_WRLOCK(&be_list);
2872         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2873                 if (!strcasecmp(name, i->name)) {
2874                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2875                         i->suspended = 0;
2876                         success = 0;
2877                 }
2878         }
2879         AST_RWLIST_UNLOCK(&be_list);
2880
2881         return success;
2882 }
2883
2884 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2885 {
2886         struct cdr_beitem *i;
2887         struct cdr_beitem *cur;
2888
2889         if (!name) {
2890                 return -1;
2891         }
2892
2893         if (!be) {
2894                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2895
2896                 return -1;
2897         }
2898
2899         i = ast_calloc(1, sizeof(*i));
2900         if (!i) {
2901                 return -1;
2902         }
2903
2904         i->be = be;
2905         ast_copy_string(i->name, name, sizeof(i->name));
2906         ast_copy_string(i->desc, desc, sizeof(i->desc));
2907
2908         AST_RWLIST_WRLOCK(generic_list);
2909         AST_RWLIST_TRAVERSE(generic_list, cur, list) {
2910                 if (!strcasecmp(name, cur->name)) {
2911                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2912                         AST_RWLIST_UNLOCK(generic_list);
2913                         ast_free(i);
2914
2915                         return -1;
2916                 }
2917         }
2918
2919         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2920         AST_RWLIST_UNLOCK(generic_list);
2921
2922         return 0;
2923 }
2924
2925 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2926 {
2927         return cdr_generic_register(&be_list, name, desc, be);
2928 }
2929
2930 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2931 {
2932         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2933 }
2934
2935 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2936 {
2937         struct cdr_beitem *match = NULL;
2938         int active_count;
2939
2940         AST_RWLIST_WRLOCK(generic_list);
2941         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2942                 if (!strcasecmp(name, match->name)) {
2943                         break;
2944                 }
2945         }
2946
2947         if (!match) {
2948                 AST_RWLIST_UNLOCK(generic_list);
2949                 return 0;
2950         }
2951
2952         active_count = ao2_container_count(active_cdrs_master);
2953
2954         if (!match->suspended && active_count != 0) {
2955                 AST_RWLIST_UNLOCK(generic_list);
2956                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2957                         name, active_count);
2958                 return -1;
2959         }
2960
2961         AST_RWLIST_REMOVE(generic_list, match, list);
2962         AST_RWLIST_UNLOCK(generic_list);
2963
2964         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2965         ast_free(match);
2966
2967         return 0;
2968 }
2969
2970 int ast_cdr_unregister(const char *name)
2971 {
2972         return ast_cdr_generic_unregister(&be_list, name);
2973 }
2974
2975 int ast_cdr_modifier_unregister(const char *name)
2976 {
2977         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2978 }
2979
2980 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2981 {
2982         struct ast_cdr *newcdr;
2983
2984         if (!cdr) {
2985                 return NULL;
2986         }
2987         newcdr = ast_cdr_alloc();
2988         if (!newcdr) {
2989                 return NULL;
2990         }
2991
2992         *newcdr = *cdr;
2993         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2994         copy_variables(&newcdr->varshead, &cdr->varshead);
2995         newcdr->next = NULL;
2996
2997         return newcdr;
2998 }
2999
3000 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
3001 {
3002         struct ast_var_t *variables;
3003
3004         if (ast_strlen_zero(name)) {
3005                 return NULL;
3006         }
3007
3008         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
3009                 if (!strcasecmp(name, ast_var_name(variables))) {
3010                         return ast_var_value(variables);
3011                 }
3012         }
3013
3014         return NULL;
3015 }
3016
3017 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
3018 {
3019         if (fmt == NULL) {      /* raw mode */
3020                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
3021         } else {
3022                 buf[0] = '\0';/* Ensure the buffer is initialized. */
3023                 if (when.tv_sec) {
3024                         struct ast_tm tm;
3025
3026                         ast_localtime(&when, &tm, NULL);
3027                         ast_strftime(buf, bufsize, fmt, &tm);
3028                 }
3029         }
3030 }
3031
3032 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
3033 {
3034         const char *fmt = "%Y-%m-%d %T";
3035         const char *varbuf;
3036
3037         if (!cdr) {
3038                 return;
3039         }
3040
3041         *ret = NULL;
3042
3043         if (!strcasecmp(name, "clid")) {
3044                 ast_copy_string(workspace, cdr->clid, workspacelen);
3045         } else if (!strcasecmp(name, "src")) {
3046                 ast_copy_string(workspace, cdr->src, workspacelen);
3047         } else if (!strcasecmp(name, "dst")) {
3048                 ast_copy_string(workspace, cdr->dst, workspacelen);
3049         } else if (!strcasecmp(name, "dcontext")) {
3050                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3051         } else if (!strcasecmp(name, "channel")) {
3052                 ast_copy_string(workspace, cdr->channel, workspacelen);
3053         } else if (!strcasecmp(name, "dstchannel")) {
3054                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3055         } else if (!strcasecmp(name, "lastapp")) {
3056                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3057         } else if (!strcasecmp(name, "lastdata")) {
3058                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3059         } else if (!strcasecmp(name, "start")) {
3060                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3061         } else if (!strcasecmp(name, "answer")) {
3062                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3063         } else if (!strcasecmp(name, "end")) {
3064                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3065         } else if (!strcasecmp(name, "duration")) {
3066                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3067         } else if (!strcasecmp(name, "billsec")) {
3068                 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);
3069         } else if (!strcasecmp(name, "disposition")) {
3070                 if (raw) {
3071                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3072                 } else {
3073                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3074                 }
3075         } else if (!strcasecmp(name, "amaflags")) {
3076                 if (raw) {
3077                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3078                 } else {
3079                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3080                 }
3081         } else if (!strcasecmp(name, "accountcode")) {
3082                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3083         } else if (!strcasecmp(name, "peeraccount")) {
3084                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3085         } else if (!strcasecmp(name, "uniqueid")) {
3086                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3087         } else if (!strcasecmp(name, "linkedid")) {
3088                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3089         } else if (!strcasecmp(name, "userfield")) {
3090                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3091         } else if (!strcasecmp(name, "sequence")) {
3092                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3093         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3094                 ast_copy_string(workspace, varbuf, workspacelen);
3095         } else {
3096                 workspace[0] = '\0';
3097         }
3098
3099         if (!ast_strlen_zero(workspace)) {
3100                 *ret = workspace;
3101         }
3102 }
3103
3104 /*!
3105  * \internal
3106  * \brief Callback that finds all CDRs that reference a particular channel by name
3107  */
3108 static int cdr_object_select_all_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                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->base->name, name))) {
3115                 return CMP_MATCH;
3116         }
3117         return 0;
3118 }
3119
3120 /*!
3121  * \internal
3122  * \brief Callback that finds a CDR by channel name
3123  */
3124 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3125 {
3126         struct cdr_object *cdr = obj;
3127         const char *name = arg;
3128
3129         if (!strcasecmp(cdr->party_a.snapshot->base->name, name)) {
3130                 return CMP_MATCH;
3131         }
3132         return 0;
3133 }
3134
3135 /* Read Only CDR variables */
3136 static const char * const cdr_readonly_vars[] = {
3137         "clid",
3138         "src",
3139         "dst",
3140         "dcontext",
3141         "channel",
3142         "dstchannel",
3143         "lastapp",
3144         "lastdata",
3145         "start",
3146         "answer",
3147         "end",
3148         "duration",
3149         "billsec",
3150         "disposition",
3151         "amaflags",
3152         "accountcode",
3153         "uniqueid",
3154         "linkedid",
3155         "userfield",
3156         "sequence",
3157         NULL
3158 };
3159
3160 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3161 {
3162         struct cdr_object *cdr;
3163         struct cdr_object *it_cdr;
3164         struct ao2_iterator *it_cdrs;
3165         char *arg = ast_strdupa(channel_name);
3166         int x;
3167
3168         for (x = 0; cdr_readonly_vars[x]; x++) {
3169                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3170                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3171                         return -1;
3172                 }
3173         }
3174
3175         it_cdrs = ao2_callback(active_cdrs_master, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3176         if (!it_cdrs) {
3177                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3178                 return -1;
3179         }
3180
3181         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3182                 ao2_lock(cdr);
3183                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3184                         struct varshead *headp = NULL;
3185
3186                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3187                                 continue;
3188                         }
3189                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->base->name)) {
3190                                 headp = &it_cdr->party_a.variables;
3191                         } else if (it_cdr->party_b.snapshot
3192                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->base->name)) {
3193                                 headp = &it_cdr->party_b.variables;
3194                         }
3195                         if (headp) {
3196                                 set_variable(headp, name, value);
3197                         }
3198                 }
3199         }
3200         ao2_iterator_destroy(it_cdrs);
3201
3202         return 0;
3203 }
3204
3205 /*!
3206  * \brief Format a variable on a \ref cdr_object
3207  */
3208 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3209 {
3210         struct ast_var_t *variable;
3211
3212         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3213                 if (!strcasecmp(name, ast_var_name(variable))) {
3214                         ast_copy_string(value, ast_var_value(variable), length);
3215                         return;
3216                 }
3217         }
3218
3219         *value = '\0';
3220 }
3221
3222 /*!
3223  * \brief Format one of the standard properties on a \ref cdr_object
3224  */
3225 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3226 {
3227         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3228         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3229
3230         if (!strcasecmp(name, "clid")) {
3231                 ast_callerid_merge(value, length, party_a->caller->name, party_a->caller->number, "");
3232         } else if (!strcasecmp(name, "src")) {
3233                 ast_copy_string(value, party_a->caller->number, length);
3234         } else if (!strcasecmp(name, "dst")) {
3235                 ast_copy_string(value, party_a->dialplan->exten, length);
3236         } else if (!strcasecmp(name, "dcontext")) {
3237                 ast_copy_string(value, party_a->dialplan->context, length);
3238         } else if (!strcasecmp(name, "channel")) {
3239                 ast_copy_string(value, party_a->base->name, length);
3240         } else if (!strcasecmp(name, "dstchannel")) {
3241                 if (party_b) {
3242                         ast_copy_string(value, party_b->base->name, length);
3243                 } else {
3244                         ast_copy_string(value, "", length);
3245                 }
3246         } else if (!strcasecmp(name, "lastapp")) {
3247                 ast_copy_string(value, party_a->dialplan->appl, length);
3248         } else if (!strcasecmp(name, "lastdata")) {
3249                 ast_copy_string(value, party_a->dialplan->data, length);
3250         } else if (!strcasecmp(name, "start")) {
3251                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3252         } else if (!strcasecmp(name, "answer")) {
3253                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3254         } else if (!strcasecmp(name, "end")) {
3255                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3256         } else if (!strcasecmp(name, "duration")) {
3257                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3258         } else if (!strcasecmp(name, "billsec")) {
3259                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3260         } else if (!strcasecmp(name, "disposition")) {
3261                 snprintf(value, length, "%u", cdr_obj->disposition);
3262         } else if (!strcasecmp(name, "amaflags")) {
3263                 snprintf(value, length, "%d", party_a->amaflags);
3264         } else if (!strcasecmp(name, "accountcode")) {
3265                 ast_copy_string(value, party_a->base->accountcode, length);
3266         } else if (!strcasecmp(name, "peeraccount")) {
3267                 if (party_b) {
3268                         ast_copy_string(value, party_b->base->accountcode, length);
3269                 } else {
3270                         ast_copy_string(value, "", length);
3271                 }
3272         } else if (!strcasecmp(name, "uniqueid")) {
3273                 ast_copy_string(value, party_a->base->uniqueid, length);
3274         } else if (!strcasecmp(name, "linkedid")) {
3275                 ast_copy_string(value, cdr_obj->linkedid, length);
3276         } else if (!strcasecmp(name, "userfield")) {
3277                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3278         } else if (!strcasecmp(name, "sequence")) {
3279                 snprintf(value, length, "%u", cdr_obj->sequence);
3280         } else {
3281                 return 1;
3282         }
3283
3284         return 0;
3285 }
3286
3287 /*! \internal
3288  * \brief Look up and retrieve a CDR object by channel name
3289  * \param name The name of the channel
3290  * \retval NULL on error
3291  * \retval The \ref cdr_object for the channel on success, with the reference
3292  *      count bumped by one.
3293  */
3294 static struct cdr_object *cdr_object_get_by_name(const char *name)
3295 {
3296         char *param;
3297
3298         if (ast_strlen_zero(name)) {
3299                 return NULL;
3300         }
3301
3302         param = ast_strdupa(name);
3303         return ao2_callback(active_cdrs_master, 0, cdr_object_get_by_name_cb, param);
3304 }
3305
3306 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3307 {
3308         struct cdr_object *cdr;
3309         struct cdr_object *cdr_obj;